从数据模型创建FormBuilder组时如何添加验证器?

时间:2017-10-05 13:43:27

标签: angular validation angular-reactive-forms

根据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())
});

如果我从数据模型创建表单组,如何添加验证器?

1 个答案:

答案 0 :(得分:1)

根据the FormBuilder sourcegroup采用第二个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)]);