我想添加自定义验证器以防止表单切换到下一步。当我使用FormGroups时一切正常,但是当我必须使用FormArray时我无法实现验证。
我已经尝试过至少两种在表单初始化时分配验证器的变体:
statuses: this._formBuilder.array([this.createStatus()], defaultStatusValidator())
this.productionLineStatuses = this._formBuilder.group({statuses: this._formBuilder.array([this.createStatus()])},
{validator: defaultStatusValidator()});
但是这种尝试会导致错误(可能是在投放验证器时):
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)
在以下情况下,不会引发错误,但是验证器也无法正常工作。 这是我的代码其余部分和自定义验证器:
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?
答案 0 :(得分:0)
您已经考虑过您的FormArray是FormControls的FormArray还是FormGroups的FormArray,但是问题是您如何遍历控件,
两者的简单示例
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
中查看示例注意:要创建表单,我使用FormGroup,FormControl和FormArray的构造函数,但您也可以使用FormBuilder。
注意2:不必将FormArray放在FormGroup中