Angular Create Custom Validation

Angular provides only four types of Validations but if you need any other validation then you can create custom validation. There are some steps to create the validations.

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

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

Step 2) Now, add the below code into 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" class="input-bordered form-control" />
<div *ngIf="submitted && formFieldValues.userAge.errors" class="invalid-feedback">
    <div *ngIf="formFieldValues.userAge.errors.required">User Age is required</div>
    <div *ngIf="formFieldValues.userAge.errors.pattern">User Age must be  numeric</div>
    <div *ngIf="formFieldValues.userAge.errors.ageGreaterThanEighteen">User Age must be greater than 18</div>
 </div>

Step 5) Now, open the URL on the browser.


http://localhost:4200/users

Step 5) When user fill the age less then 18 then show validation in the userAge field.