Angular Custom Validation (2024)

Angular Custom Validation (1)

Angular is a powerful front-end framework that allows developers to build dynamic and interactive web applications. One of the key features of Angular is its form handling capabilities. Angular provides a set of built-in validators to perform common form validations such as required fields, email format, and min/max length. However, there are cases where you need to implement custom validation logic to meet your application’s specific requirements. In this article, we will explore how to create custom validators in Angular with examples.

Custom validators in Angular are essential when you encounter validation scenarios that cannot be achieved using the built-in validators. Some common use cases for custom validators include:

  1. Password Confirmation: You might want to ensure that two password input fields match each other.
  2. Unique Username: Checking if a chosen username is unique in your application’s database.
  3. Conditional Validation: Implementing complex validation rules based on the state of other form controls.

To create a custom validator in Angular, you need to define a function that performs the validation logic and returns a validation error object if the validation fails. This function should adhere to the signature of ValidatorFn or AsyncValidatorFn based on whether your validation logic is synchronous or asynchronous.

Synchronous Custom Validator

Here’s an example of a synchronous custom validator that checks if a name contains only letters:

import { AbstractControl } from "@angular/forms";export default function LetterValidator( control: AbstractControl): { [key: string]: any } | null { if (!control.value) return null; const reg = new RegExp("^[a-zA-Z]+$"); return reg.test(control.value) ? null : { invalidSymbols: true };}

In this example, we define a letterValidatorfunction that returns a validator function. The validator function takes a form control as an argument and checks if it contains only letters. If not, it returns a validation error object with a invalidSymbols property.

Usage:

import { FormGroup, FormBuilder, Validators } from "@angular/forms";import LetterValidator from "../letters.validator";@Component({ selector: "app-user", templateUrl: "./user.component.html", styleUrls: ["./user.component.scss"],})export class UserComponent { submitForm!: FormGroup; constructor(private fb: FormBuilder) { this.submitForm = this.fb.group({ name: ["", [LetterValidator]], // add validator here }); }}

Now if form control has invalid symbols we will see error message

<form [formGroup]="submitForm"> <div> <mat-form-field> <mat-label>Name</mat-label> <input matInput type="text" placeholder="Name" formControlName="name" /> <mat-error *ngIf="submitForm.controls['name'].hasError('invalidSymbols')"> Only letters are allowed </mat-error> </mat-form-field> </div></form>

And theinvalidSymbols property comes from LetterValidator

Angular Custom Validation (2)

Usage of Custom Validator

Now, let’s assume our validator depends on the value of another form control. A good example is the password confirmation input

So we need to create a custom validation to confirm that two password fields match each other. First, let’s create the custom validator function for password confirmation:

import { AbstractControl, ValidationErrors, ValidatorFn } from "@angular/forms";export function passwordConfirmationValidator( controlName: string, matchingControlName: string): ValidatorFn { return (formGroup: AbstractControl): ValidationErrors | null => { const passwordControl = formGroup.get(controlName); const confirmPasswordControl = formGroup.get(matchingControlName); if (!passwordControl || !confirmPasswordControl) { return null; } if (passwordControl.value !== confirmPasswordControl.value) { confirmPasswordControl.setErrors({ passwordMismatch: true }); } else { confirmPasswordControl.setErrors(null); } return null; };}

In this code, we define a passwordConfirmationValidator function that takes two control names as arguments: controlName for the password field and matchingControlName for the confirmation password field. This function returns a validator function that compares the values of these two fields and sets a passwordMismatch error if they do not match.

Now, let’s use this custom validator in an Angular component:

import { passwordConfirmationValidator } from "../confirm-password.validator";@Component({ selector: "app-register", templateUrl: "./register.component.html",})export class UserComponent { registrationForm!: FormGroup; constructor(private fb: FormBuilder) { this.registrationForm = this.fb.group( { password: ["", [Validators.required, Validators.minLength(3)]], confirmPassword: ["", [Validators.required]], }, { validator: passwordConfirmationValidator("password", "confirmPassword"), } ); }}

In this component, we import and use the passwordConfirmationValidator function to create a custom validation rule for the password confirmation. We apply this custom validator to the form group by passing the control names ('password' and 'confirmPassword') to the passwordConfirmationValidator function within the validator option.

Lastly, you can display an error message in your template when the passwords don’t match:

<form [formGroup]="registrationForm"> <div> <mat-form-field> <mat-label>Password</mat-label> <input matInput formControlName="password" type="password" /> </mat-form-field> </div> <mat-form-field> <mat-label>Confirm Password</mat-label> <input matInput formControlName="confirmPassword" type="password" /> <mat-error *ngIf="registrationForm.controls['confirmPassword'].hasError('passwordMismatch')"> Passwords do not match. </mat-error> </mat-form-field> <p> <button type="submit" [disabled]="registrationForm.invalid">Register</button> </p></form></div>

In the template, we use the *ngIf directive to display an error message when the 'confirmPassword' field has the 'passwordMismatch' error set, indicating that the passwords do not match.

With this custom validation in place, your Angular registration form will ensure that the user enters the same password in both the ‘password’ and ‘confirmPassword’ fields

Angular Custom Validation (3)

In this example we will check checking if a chosen username is unique in our application’s database.

For asynchronous validation, you can use the AsyncValidatorFn. Here's an example of an asynchronous custom validator that checks if a username is already taken:

import { AbstractControl, ValidationErrors, AsyncValidatorFn,} from "@angular/forms";import { UserService } from "./services/user.service";import { Observable, of } from "rxjs";import { map, catchError } from "rxjs/operators";export function uniqueUsernameValidator( userService: UserService): AsyncValidatorFn { return (control: AbstractControl): Observable<ValidationErrors | null> => { const username = control.value as string; return userService.getUser(username).pipe( map((user) => { // for testing we will return false if username is 'test' const isTaken = username === "test" ? false : !!user; return isTaken ? { usernameTaken: true } : null; }), catchError(() => of(null)) // In case of an error, we assume the username is available. ); };}

In this example, we define an uniqueUsernameValidator function that returns an asynchronous validator function. This validator function checks if the username already exists by calling a userService method. It returns an observable that emits a validation error object if the username is taken or null if it's available.

@Component({ selector: "app-user", templateUrl: "./user.component.html",})export class UserComponent { userForm!: FormGroup; constructor(private fb: FormBuilder) { this.userForm = this.fb.group({ name: [ "", [Validators.required], [uniqueUsernameValidator(this.userService)], ], }); }}

Html

<mat-form-field> <mat-label>User name</mat-label> <input matInput type="text" placeholder="Name" formControlName="name" /> <mat-error *ngIf="userForm.controls['name'].hasError('usernameTaken')"> Username is taken </mat-error></mat-form-field>

Example

Angular Custom Validation (4)

Async validator example

Note: When the request is pending, userForm.invalid becomes false

Custom validators are a powerful tool in Angular for handling complex form validation requirements. By creating custom validators, you can tailor your validation logic to the specific needs of your application. Whether you need to perform synchronous or asynchronous validation, Angular provides a flexible framework to implement and use custom validators effectively. So, don’t hesitate to leverage custom validators to enhance the user experience in your Angular applications.

Angular Custom Validation (2024)
Top Articles
Helium
Colossians 3 | NIV Bible | YouVersion
Swimgs Yuzzle Wuzzle Yups Wits Sadie Plant Tune 3 Tabs Winnie The Pooh Halloween Bob The Builder Christmas Autumns Cow Dog Pig Tim Cook’s Birthday Buff Work It Out Wombats Pineview Playtime Chronicles Day Of The Dead The Alpha Baa Baa Twinkle
Craigslist Motorcycles Jacksonville Florida
Wausau Marketplace
Sam's Club Gas Price Hilliard
Best Transmission Service Margate
King Fields Mortuary
Mens Standard 7 Inch Printed Chappy Swim Trunks, Sardines Peachy
Video shows two planes collide while taxiing at airport | CNN
1-833-955-4522
Kylie And Stassie Kissing: A Deep Dive Into Their Friendship And Moments
Jbf Wichita Falls
Walgreens Alma School And Dynamite
Www Craigslist Madison Wi
Who is Jenny Popach? Everything to Know About The Girl Who Allegedly Broke Into the Hype House With Her Mom
Kentuky Fried Chicken Near Me
Move Relearner Infinite Fusion
Strange World Showtimes Near Savoy 16
Acurafinancialservices Com Home Page
Intel K vs KF vs F CPUs: What's the Difference?
Missing 2023 Showtimes Near Grand Theatres - Bismarck
James Ingram | Biography, Songs, Hits, & Cause of Death
Loopnet Properties For Sale
Ravens 24X7 Forum
Moonrise Time Tonight Near Me
Khatrimmaza
Wega Kit Filtros Fiat Cronos Argo 1.8 E-torq + Aceite 5w30 5l
Grandstand 13 Fenway
Southern Democrat vs. MAGA Republican: Why NC governor race is a defining contest for 2024
Greencastle Railcam
Compress PDF - quick, online, free
Tamilyogi Ponniyin Selvan
Skip The Games Ventura
Ludvigsen Mortuary Fremont Nebraska
Bismarck Mandan Mugshots
10 games with New Game Plus modes so good you simply have to play them twice
Telugu Moviez Wap Org
Craigslist Tulsa Ok Farm And Garden
Engr 2300 Osu
Peace Sign Drawing Reference
Victoria Vesce Playboy
Aloha Kitchen Florence Menu
Unblocked Games 6X Snow Rider
Plumfund Reviews
Hughie Francis Foley – Marinermath
How to Do a Photoshoot in BitLife - Playbite
Puss In Boots: The Last Wish Showtimes Near Valdosta Cinemas
Craigslist Pets Lewiston Idaho
Prologistix Ein Number
Tenichtop
Island Vibes Cafe Exeter Nh
Latest Posts
Article information

Author: Dan Stracke

Last Updated:

Views: 5822

Rating: 4.2 / 5 (63 voted)

Reviews: 86% of readers found this page helpful

Author information

Name: Dan Stracke

Birthday: 1992-08-25

Address: 2253 Brown Springs, East Alla, OH 38634-0309

Phone: +398735162064

Job: Investor Government Associate

Hobby: Shopping, LARPing, Scrapbooking, Surfing, Slacklining, Dance, Glassblowing

Introduction: My name is Dan Stracke, I am a homely, gleaming, glamorous, inquisitive, homely, gorgeous, light person who loves writing and wants to share my knowledge and understanding with you.