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



我可以在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为true的情况下验证PerHour

在这种情况下,表单正在检查PerHour字段pricePerHour为false或true(可见/禁用(。表示布尔变量pricePerHourpriceValidator((内始终为false。

我也检查了以下内容,但没有工作:-

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

对此有任何建议。

这太简单了,我让它变得如此复杂。我只是在下面添加了我调用change函数的行。解决:轻视_微笑:

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

最新更新