How to add Validators Dynamically using SetValidators in Angular

We can add Validators dynamically using the SetValidators or SetAsyncValidators. This method is available to FormControl, FormGroup & FormArray.

There are many use cases where it is required to add/remove validators dynamically to a FormControl or FormGroup. Usually when you have a Form Field, whose value depends on another Form Field.

Adding the Validators Using the SetValidators

Syntax

The setValidators programmatically adds the sync validators. This method will remove all the previously added sync or async validators.

setValidators(newValidator: ValidatorFn | ValidatorFn[]): void

Examples:

setAsyncValidators

The setAsyncValidators programmatically add the Async validators.

setValidators overwrites all existing Validators. Hence it is very important to include all the validators that we want in the setValidators method

Removing Validators Using clearValidators

There is no option that exists, which can remove an individual validator. Use clearValidators to remove all the validators of a control.

Update Validation Status

Removing or adding the validators does not change the validity status of the form or the control immediately. The Validators run only when we change the value of the field.

We can force angular to run the validations using the updateValueAndValidity method.

SetValidators Example

The following example, shows how to use the SetValidators in Angular

We have two fields email & mobile.

The user needs to choose, how he wants the system to notify him, using the drop-down field notifyVia. The drop-down has two options email & Mobile.

If the user chooses email, then we need to make the email field as a Required field. If he chooses the Mobile, then we must make the mobile field as Required field.

We subscribe to the valueChanges event of the notifyVia to listen for changes and invoke the changeValidators method.

In the changeValidators method, we check the value of notifyVia and add or remove the required validator using the setValidators. We also add the email validator (for email field) or MinLength validator (for mobile field). To remove the validator, we use the method clearValidators()

Finally, we use the updateValueAndValidity method, which forces the angular to update the validity status of the control.

The component template

References

  1. SetValidators
  2. SetAsyncValidators
  3. ClearValidators
  4. UpdateValueAndValidity

Leave a Comment

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top