Form Array所有控件都需要条件验证



我有一个表单Array,它必须基于变量进行控制,现在我编写了自定义验证器,如下所示

recurringValidator(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
if (!control.value) {
return null;
}
if (this.myVariable === 'constant1') {
return Validators.required;
}
return null;
};
}

现在,这将检查"myVariable"的值,并放入所需的值,但不知何故,它不起作用,我在下面添加了这个自定义验证器

const fbGroup = this.fb.group({
recurringControl1: this.fb.control('', [this.recurringValidator()]),
recurringControl2: this.fb.control('', [this.recurringValidator()]),
recurringControl3: this.fb.control('', [this.recurringValidator()])
});
this.myForm = this.fb.group({
control1: fb.control('', [this.recurringValidator()]),
groupcontrol1: fb.array([])
});

当我点击提交时,即使myVariable值是'constant1',表单也是有效的。请提出任何建议或修改。

这是stackblitz链接https://stackblitz.com/edit/angular-form-array-validators?

您正在传递验证器引用,而不是执行并返回值。如果你直接使用验证器,这将是正确的方法,但由于你使用的是自定义验证器,验证器将由Angular(你的验证器(调用,但对于所需的验证器,你是需要调用它的人,所以尝试替换:

recurringValidator(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
if (!control.value) {
return null;
}
if (this.myVariable === 'constant1') {
return Validators.required;
}
return null;
};
}

收件人:

recurringValidator(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
// if (!control.value) {
//   return null;
// }
if (this.myVariable === 'constant1') {
// Invoking the validator ourselves
return Validators.required(control);
}
return null;
};
}

此外,我认为不需要第一个条件!control.value,无论myVariable的内容如何,它都会为空值返回null,所以我注释掉了。

StackBlitz

您不能返回Validator,否则不能返回对象并使自定义验证器

如果你的变量没有随时间变化,你可以做

recurringValidator(necesary:boolean): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
if (control.value) { //<--if has any value return null
return null;
}
if (necesary) {
return {required:true} //<--see that you return an object, NOT Validators.required
}
return null;
};
}

你使用

control=new FormControl(null,this.recurringValidator(this.myVariable!='constant1'))

请注意,如果在创建formControl后更改myVariable的值,则验证程序将获得变量的实际值

如果你需要考虑变量和变量在你需要的时间内的变化;绑定(这个(";创建表单时

recurringValidator(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
if (control.value) {
return null;
}
if (this.myVariable === 'constant1') {
return {required:true} //<--see that you return an object, NOT Validators.required
}
return null;
};
}

并使用

control=new FormControl(null,this.recurringValidator().bind(this))

在这种情况下,当您更改变量时,不要忘记更新和有效性控件,例如

<button (click)="myVariable=!myVariable;
control.updateValueAndValidity()">
click
</button>

最新更新