Dynamic form validation in Angular

Sometimes it’s necessary to update a form field’sĀ validator dynamically, depending on another field value for example. This post explains how to do this.

It’s easy to set a form field’s validator by using the ‘setValidators’ method on the form control object. The ‘clearValidators’ method remove currently set validators on the other hand. The important part is calling ‘updateValueAndValidity’ afterwards, otherwise the validation changes will not take effect.

The following code will listen for changesĀ of the field ‘paymentMethod’ and set’s the ‘required’ validator on the field ‘cardNumber’ accordingly.

const cardNumberCtrl = this.formGroup.get('cardNumber');
const changes$ = this.formGroup.get('paymentMethod').valueChanges;

changes$.subscribe(val => {
  if (val === 'card') {
    cardNumberCtrl.setValidators([Validators.required]);
  } else {
    cardNumberCtrl.clearValidators();
  }
});

cardNumberCtrl.updateValueAndValidity();