繁体   English   中英

2自定义验证器无法在Angular中以反应形式工作

[英]2 Custom validator not working in reactive forms in Angular

我需要弄清楚如何在我的反应形式中添加第二个验证器。 我已经将“ AvailabilityBalanceValidator”添加到了初始化行的patchValues()中。 但是,只有第一个验证器正在工作,而第二个验证器(即AvailabilityBalanceValidator())却无法工作。 请检查此链接检查此链接

patchValues() {
    const materialForms = this.orders
      .reduce((acc, i) => [...acc, ...i.materials], [])
      .map(x => {
        return (this.fb.group({
          checkbox_value: [null],
          material_id: [{ value: x.id, disabled: true }],
          material_name: x.name,
          available_qty: 10,
          quantity: [null]
        }, [this.subFormValidator.bind(this), { validator: this.AvailabilityBalanceValidator('available_qty', 'quantity') }]));
      });

    this.myForm.setControl('rows', this.fb.array(materialForms));
    this.myForm.setValidators([this.formValidator.bind(this)])
  }

  AvailabilityBalanceValidator(campo1: string, campo2: string) {
    return (group: FormGroup): { [key: string]: any } => {
      const balance = group.controls[campo1];
      const quantity = group.controls[campo2];
      if (balance.value < quantity.value) {
        return {
          out: true
        };
      }
    };
  }

我弄清楚了为什么您的第二个验证器不起作用。 实际上,添加验证器是错误的。

您将验证器数组分配为this.fb.group()方法的第二个参数:

this.fb.group({...}, [this.subFormValidator.bind(this), { validator: this.AvailabilityBalanceValidator('available_qty', 'quantity') }];

FormBuilder.group方法接收带有两个可能的参数validatorasyncValidator的对象作为第二个参数(请参阅docs )。

要解决缺少的验证问题,您应该按照以下步骤更改代码:

this.fb.group({...}, {
    validator: Validators.compose([this.subFormValidator.bind(this), this.AvailabilityBalanceValidator('available_qty', 'quantity')])
};

更新:

subFormValidator(control: AbstractControl): { [key: string]: any } {
    return control.value.checkbox_value && 
        // Only adds the error if quantity is not set or it's an empty string
        (!control.value.quantity || control.value.quantity.length === 0)? { 'req': 'This field is required' } : null
}

并在您的html中:

<small class="form-text text-muted danger" *ngIf="row.hasError('req')">This field is required</small>

否则,如果控件有错误,则始终显示该消息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM