根据the Reactive Forms documentation,我可以从
重构我的FormGroup定义this.heroForm = this.fb.group({
name: ['', Validators.required ],
address: this.fb.group({
street: '',
city: '',
state: '',
zip: ''
})
});
到
export class Address {
street = '';
city = '';
state = '';
zip = '';
}
this.heroForm = this.fb.group({
name: ['', Validators.required ],
address: this.fb.group(new Address())
});
如果我从数据模型创建表单组,如何添加验证器?
答案 0 :(得分:1)
根据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)]);