如何在从数据模型创建FormBuilder组时添加验证器?
问题描述:
据the Reactive Forms documentation,我可以从如何在从数据模型创建FormBuilder组时添加验证器?
this.heroForm = this.fb.group({
name: ['', Validators.required ],
address: this.fb.group({
street: '',
city: '',
state: '',
zip: ''
})
});
重构我FormGroup定义来
export class Address {
street = '';
city = '';
state = '';
zip = '';
}
this.heroForm = this.fb.group({
name: ['', Validators.required ],
address: this.fb.group(new Address())
});
如果我从一个数据模型创建表单组,如何添加验证?
答
根据the FormBuilder source,group
需要第二个extra
参数,您可以在其中定义验证器。 Todd Motto has an article on how to use it提示如下:
export class Address {
street = '';
city = '';
state = '';
zip = '';
}
this.heroForm = this.fb.group({
name: ['', Validators.required ],
address: this.fb.group(new Address(), { validator: this.myValidator })
});
this.myValidator = (control: AbstractControl): {[key: string]: boolean} => {
const city= control.get('city');
const state= control.get('state');
...
if (allTheControlsAreValid) return null;
else return { myCustomError: foo};
};
这使您可以验证表单组,而不是控制。如果你想在各个控件设置验证,您可以通过编程设置它们创建formGroup
后:
this.heroForm.get('address').get('city').setValidators([Validators.required, Validators.maxLength(30)]);
我觉得你可以在setter方法使用观察者模式的混合搭配使用正则表达式。 就像检查模型的setters中的有效性一样 –