如何将自定义验证器添加到FormArray? [英] How to add custom validator to a FormArray?
问题描述
我想添加自定义验证器以防止表单切换到下一步.当我使用FormGroups时,一切都很好,但是当我必须使用FormArray时,我无法实现验证.
I want to add custom validator to form in order to prevent mat-step switching to next step. All works well when I use FormGroups but I fail to achieve validation when I have to use FormArray.
我已经尝试过至少两种在表单初始化时分配验证器的变体:
I've tried at least two variants of assigning validator on form initialization:
- 内部数组
statuses: this._formBuilder.array([this.createStatus()], defaultStatusValidator())
- 内部父级数组
this.productionLineStatuses = this._formBuilder.group({statuses: this._formBuilder.array([this.createStatus()])},
{validator: defaultStatusValidator()});
this.productionLineStatuses = this._formBuilder.group({statuses: this._formBuilder.array([this.createStatus()])},
{validator: defaultStatusValidator()});
但是这种尝试会导致错误(可能是在投放验证器时):
But this attempts are causing error (probably when casting validator):
TypeError: Cannot convert undefined or null to object
at Function.keys (<anonymous>)
at FormGroup.validate [as validator] (default-status.directive.ts:6)
at FormGroup._runValidator (forms.js:3438)
at FormGroup.updateValueAndValidity (forms.js:3399)
at new FormGroup (forms.js:4097)
at FormBuilder.group (forms.js:7578)
at CreateProductionLineComponent.ngOnInit (create-production-line.component.ts:31)
在以下情况下,不会引发错误,但是验证器也无法正常工作. 这是我的代码其余部分和自定义验证器:
In the following case error is not thrown, but validator is not working too. Here is rest of my code and my custom validator:
ngOnInit() {
this.productionLineDetails = this._formBuilder.group({
productType: ['', Validators.required],
language: ['', Validators.required],
name: ['', Validators.required],
description: [''],
});
this.productionLineStatuses = this._formBuilder.group({
statuses: this._formBuilder.array([
this.createStatus()
])
}, defaultStatusValidator());
this.statuses = this.productionLineStatuses.get('statuses') as FormArray;
this.statusError = false;
}
验证器:
export function defaultStatusValidator(): ValidatorFn {
return function validate (statuses: FormArray) {
let defaultCounter = 0;
Object.keys(statuses.value.controls).forEach(key => {
const control = statuses.value.controls[key];
if (control.value.default == true) {
defaultCounter ++;
}
});
return (defaultCounter > 1) ? {moreThanOneStatusIsDefault: true} : null;
};
}
我应该如何正确地将验证器添加到FormArray?
How should I properly add validator to FormArray?
推荐答案
您已经考虑过FormArray是FormControls的FormArray还是FormGroups的FormArray,但是问题是如何遍历控件,
You has consider if your FormArray is a FormArray of FormControls or a FormArray of FormGroups, but the problem is how you iterate over the controls,
两者的简单示例
export function customValidateArray(): ValidatorFn {
return (formArray:FormArray):{[key: string]: any} | null=>{
let valid:boolean=true;
formArray.controls.forEach((x:FormControl)=>{
valid=valid && x.value=="a"
})
return valid?null:{error:'Not all a'}
}
};
export function customValidateArrayGroup(): ValidatorFn {
return (formArray:FormArray):{[key: string]: any} | null=>{
let valid:boolean=true;
formArray.controls.forEach((x:FormGroup)=>{
valid=valid && x.value.name=="a"
})
return valid?null:{error:'Not all name are a'}
}
};
您可以在 stackblitz 中查看示例a>
You can see an example in stackblitz
注意:要创建表单,我使用FormGroup,FormControl和FormArray的构造函数,但您也可以使用FormBuilder.
NOTE: To create the form, I use the constructor of FormGroup, FormControl and FormArray, but you can use FormBuilder too.
注意2:不必将FormArray放在FormGroup中
NOTE 2: it's not necesary enclose a FormArray in a FormGroup
这篇关于如何将自定义验证器添加到FormArray?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!