How do I add validators when creating FormBuilder groups from a data model?

Viewed 2656

According to the Reactive Forms documentation, I can refactor my FormGroup definitions from

this.heroForm = this.fb.group({
  name: ['', Validators.required ],
  address: this.fb.group({
    street: '',
    city: '',
    state: '',
    zip: ''
  })
});

to

export class Address {
  street = '';
  city   = '';
  state  = '';
  zip    = '';
}

this.heroForm = this.fb.group({
  name: ['', Validators.required ],
  address: this.fb.group(new Address())
});

If I create a form group from a data model, how do I add validators?

1 Answers

According to the FormBuilder source, group takes a second extra parameter in which you can define validators. Todd Motto has an article on how to use it which suggests the following:

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};
};

This allows you to validate the form group, but not the controls. If you want to set validators on the individual controls, you can set them programatically after the formGroup is created:

this.heroForm.get('address').get('city').setValidators([Validators.required, Validators.maxLength(30)]);
Related