Angular13 Create Custom Validation

Angular13 provides only four types of Validations but if you need any other validation then you can create custom validation.

To create a custom validation in Angular, you can follow the below steps:

You know we have users component which is defined already.
As You know, the Users Component has a userAge field and we need to define a minimum age limit of 18 for this field, so we create a custom validation through the below steps.

Step 1) Firstly create a folder that has name validators and after that, we create a file in this folder, which has the name custom.validators.ts file

Step 2) Now, add the below code into the custom.validators.ts file.


import { AbstractControl, ValidationErrors } from '@angular/forms';
export class CustomValidators {

  public static ageGreaterThanEighteen(control: AbstractControl): ValidationErrors | null {

    if(control.value <= 18 && control.value !==''){

      return {ageGreaterThanEighteen : true}
    }

    return null;

  }
}

Note:- AbstractControl is used to control the field value.

Step 3) Add custom validation into the users.component.ts file

Step a) include custom validators class through below code.


import {CustomValidators} from '../validators/custom.validators';

Step b) Now add the custom validation into form field.


 this.userForm = this.fb.group({
      userName: ['', [Validators.required]],
      userAge: ['', [Validators.required, Validators.pattern(/^-?(0|[1-9]\d*)?$/), CustomValidators.ageGreaterThanEighteen]]
    });

Step 4) Add custom validation into the users.component.html file


<input type="text" formControlName="userAge"  [ngClass]= "{ 'is-invalid': submitted && formData['userAge'].errors}"/>             
                <div *ngIf="submitted && formData['userAge'].errors" class="invalid-feedback">
                  <div *ngIf="formData['userAge'].errors['required']">User Age is required</div>
                  <div *ngIf="formData['userAge'].errors['pattern']">User Age must be  numeric</div>
                  <div *ngIf="formData['userAge'].errors['ageGreaterThanEighteen']">User Age must be  greater than 18</div>
                </div> 

Step 5) Now, You have to open the URL in the browser.


http://localhost:4200/

Step 5) When the user fills in the age less than or equal to 18 then show validation in the userAge field.