具有自定义验证功能的离子验证

ionic validation with custom validation function

我可以在 FormBuilder 和 FormControl 的帮助下验证表单,如下所示

this.pricePerHour = false/true; //based on visible or not

this.myForm = this.formBuilder.group({
      Description: new FormControl('', Validators.required),
      PerHour: new FormControl('', Validators.compose([this.PriceValidator(this.pricePerHour)]))
     //this.pricePerHour is a boolean variable, initially false
    });


priceValidator(argPerHour: boolean): ValidatorFn {
    return (control: AbstractControl): { [key: string]: boolean } | null => {
      console.log(argPerHour); 
     // always false even on true
      if (control.value == '' && argPerHour == true) {
        return { valid: true };
      }
      return null;
    };
    }

这里我只想在 pricePerHour 为真时验证 PerHour。

在这种情况下,表单正在检查 PerHour 字段 pricePerHour 是假还是真 (visible/disable)。 意味着布尔变量 pricePerHourpriceValidator().

中始终为 false

我也检查了下面但没有工作:-

   this.myForm = this.formBuilder.group({
   Description: new FormControl('', Validators.required),
   PerHour: new FormControl('', Validators.compose([this.pricePerHour ==    
     true ? null : Validators.required]))
   });

对此有任何建议。

原来如此简单,我却把它搞得如此复杂。 我只是在调用 change 函数的地方添加了下面几行。已解决:slight_smile:

this.myForm.get('PerHour').clearValidators();
this.myForm.get('PerHour').setValidators([Validators.required]);
this.myForm.get('PerHour').updateValueAndValidity();