Home Angular Tutorials Add and Remove Validators dynamically in Angular

Add and Remove Validators dynamically in Angular

by aouidane.med.amine
276,810 views 10 min read

In this tutorial , we are going to learn how to add and remove validators dynamically using the reactive-forms approach.

We are going to create a real life example to see the impact in the form every time we add or remove validators.

Table of Contents

How to add and remove validators dynamically

Generally , when we create a user interface that contains user interactions , especially when we need to collect data inputs using the forms we will certainly have many problems if we do not secure and control the data input of the user. 

Angular provides us the formControl as an efficient tool  allowing us to add and remove validators dynamically to secure and control the user data inputs swiftly.

Angular fromControl provides us 5 interesting methods to add and remove validators dynamically :

  • setvalidators : used to add or replace the existing sync validator in the formControl
  • setAsyncValidators : used to add or replace the existing async validators in the formControl
  • clearValidators : used to remove all the sync validators in the formControl
  • clearAsyncValidators: used to remove all the async validators in the formControl
  • updateValueAndValidity: used to apply the modifications when we add and remove validators dynamically at the run time.

How to use setValidators() method

Angular formControl provides the setValidators method to set the new validator.

if the formControl contains already form validations , angular will only set the new formControl validators otherwise angular will remove the existing formControl validators and replace them by the new validators.

don’t forget to call the updateValueAndValidity method every time we add and remove validators to apply the modifications.

Syntax : 

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

setValidators Example

In this example we are going to see how to use the setValidators methods to add new formControl validators dynamically.

By default , we have a simple formGroup that was created through the formBuilder.

in this form we have added some default validators for each formControl.

				
					  initializeForm(): void {
    this.userForm = this.formBuilder.group({
      pseudo: new FormControl('XperTuto', Validators.required),
      name: new FormControl('Aouidane', Validators.required),
      age: new FormControl('15'),
      email: new FormControl(''),
    });
  }
				
			

Now we need to bind the formGroup property and add the validations error messages

				
					 <!--app.component.html -->
<form [formGroup]="userForm" (ngSubmit)="adduser()">

  <mat-card>
    <mat-form-field appearance="fill">
      <mat-label>Pseudo*</mat-label>
      <input matInput type="text" formControlName="pseudo" placeholder="Pseudo">
      <mat-error *ngIf="userForm.controls['pseudo'].hasError('required')">
        <strong>
          the pseudo is required
        </strong>
      </mat-error>
    </mat-form-field>
    <mat-form-field appearance="fill">
      <mat-label>Name*</mat-label>
      <input matInput type="text" formControlName="name" placeholder="Name">
      <mat-error *ngIf="userForm.controls['name'].hasError('required')">
        <strong>
          the user Name is required
        </strong>
      </mat-error>
    </mat-form-field>
    <mat-form-field appearance="fill">
      <mat-label>Age</mat-label>
      <input matInput type="text" formControlName="age" placeholder="Age">
      <mat-error *ngIf="userForm.controls['age'].hasError('min') || userForm.controls['age'].hasError('max')">
        <strong>
          the user Age must be between 18 and 90
        </strong>
      </mat-error>
    </mat-form-field>
    <mat-form-field appearance="fill">
      <mat-label>Email</mat-label>
      <input matInput type="text" formControlName="email" placeholder="Email">
      <mat-error *ngIf="userForm.controls['email'].hasError('exist')">
        <strong>
          the email is already exist
        </strong>
      </mat-error>
    </mat-form-field>
  </mat-card>

  <mat-card-actions>
    <button type="submit" mat-raised-button color="primary">Add</button>
    <button (click)="setAgeSyncValidator()" mat-raised-button color="primary">set Age Sync Validator</button>
    <button (click)="removeAgeSyncValidator()" mat-raised-button color="primary">remove Age Sync Validator</button>
  </mat-card-actions>

</form>

				
			

we will have some thing like this as a result : 

add_and_remove_validators

As you see , we have added the error message in the template concerning the user Age ,but we don’t see any error message in the form view, that because the formControl doesn’t have a validator yet.

using the setValidators method we will set the new validators for the formControl “Age” and we set the min age 18 and max age 90.

				
					  setAgeSyncValidator() {
    this.userForm.controls['age'].setValidators([Validators.min(18), Validators.max(90)]);
    this.userForm.controls['age'].updateValueAndValidity();
  }
				
			

Now , when we click the “set Age Sync Validator” button , we will call the setAgeSyncValidator method and we will set the new validations rules. While the existing age is under 18 , the formControl will become invalid and we will see the error message in the screen.

add_and_remove_validator_age

now the formControl contains validators with min 18 and max 90.

So, using the same method , we will replace the formControl validators of the same formControls “age” that already contain validators and we set min age 15 instead of 18

				
					    this.userForm.controls['age'].setValidators([Validators.min(15), Validators.max(90)]);
				
			

Now , if we click the “set age  sync validator”  button again , we will set the new validation rules and we set the min age 15 , so the formControl become valid and the error message will disappear.

How to use clearValidators() method

Angular formControl provides us also the clearValidators methods that allows us to remove all the sync validators in the formControls.

Syntax :

clearValidators(): void 

clearValidators() Example

We are going to use the previous example and suppose that we have already created the formGroup and we have set all the needed validators.

Now , if we want to remove the validator of any formControl , we just need to access to the formControl and call the clearValidators method :

				
					  removeAgeSyncValidator() {
    this.userForm.controls['age'].clearValidators();
    this.userForm.controls['age'].updateValueAndValidity();
  }
				
			

How to use setAsyncValidators() Method

In the previous sections we have seen how to use the setValidators method, but this method can be used only with the sync validators.

That’s why angular provides us another method to handle the async validators too.

setAsyncValidators used to add or replace the current formControl async validators.

Syntax :

setAsyncValidators(newValidator: AsyncValidatorFn | AsyncValidatorFn[]): void 

setAsyncValidators() Example

In this part ,we will use the same previous example , we will suppose that we already have a formGroup that contains some validators.

Now , we will use the setAsyncValidators to set the new formControl validators and we will use an async function to validate the formControl

We suppose that we already have an async function that allows us to check if the Email already exists in the database or not. 

Now we can use the setAsyncValidator method and pass the async function in the parameter.

				
					  setAsyncEmailValidator() {
    this.userForm.controls['email'].setAsyncValidators([checkEmailValidator(this.ldapService)]);
    this.userForm.controls['email'].updateValueAndValidity();
  }
				
			

How to use clearAsyncValidators() Method

We have seen in the previous sections how to use the clearValidators methods , but this method allows us to remove only the sync validators.

That why angular provides us the clearAsyncValidators method to remove the async validators in the formControl  

syntax :

clearAsyncValidators(): void 

clearAsyncValidators () Example

Based on the previous example that contains a formGroup and asyncValidators , now we will try to remove the existing async Validators using the clearAsyncValidators method.

				
					  removeEmailAsyncValidator() {
    this.userForm.controls['email'].clearAsyncValidators();
    this.userForm.controls['age'].updateValueAndValidity();
  }
				
			

How to use setErrors() Method

In the same cases, we find ourselves obliged to add or remove dynamically the formControl errors based on the same complicated conditions.

That’s why angular formControl provides us the setErrors() method that allows us to add or remove dynamically the formControl errors.

setErrors() Example

In this example we are going to add a new custom error called “pseudo_already_exist

To do that we need only to pass the error object to the setErrors() method.

				
					  // app.component.ts
  setError() {
    this.userForm.controls['pseudo'].setErrors({pseudo_already_exist: true})
  }
				
			
				
					   
   <!-- app.component.html -->
    <mat-form-field appearance="fill">
      <mat-label>Pseudo*</mat-label>
      <input matInput type="text" formControlName="pseudo" placeholder="Pseudo">
      <mat-error *ngIf="userForm.controls['pseudo'].hasError('pseudo_already_exist')">
        <strong>
          the pseudo is already exist
        </strong>
      </mat-error>
    </mat-form-field>
				
			

To remove the formControl errors, we just need to pass an empty object to the setErrors() method.

References

Clone the Project

To download and run the example, please follow the steps :

1- Clone the source code from XperTuto git repository using the following command : 

git clone https://github.com/www-xperTuto-com/add_and_remove_validators_dynamically.git

2- Install the node dependencies using NPM command line  : npm install

3- Run the application using the following command : ng serve 

4- Access to the project through the URL : http://localhost:4200 

Read More About Angular Forms :

Recapitulation

In this angular tutorial , we have seen how to add and remove validators dynamically using formControl methods.

We have created an example that regrouping all the methods to see the result of every action in the screen.

We have used the setValidator to set a new validator for a formControl that does not contain a validator and we have replaced it later using the same method ,and we did the same thing with the setAsyncValidator to handle the async validator of the formControl .

finally , we have seen how to set and remove a custom validator manually using the setErrors() method,  that my be used for some particular cases.

I hope you enjoy reading this Tutorial.

You may also like