Custom Validation In Angular Reactive Forms

Introduction

 
In this article, we will learn about validations in the reactive form in Angular. We will create a simple user registration form and implement some inbuilt validations on it. Along with the inbuilt validations, we will also implement some custom validations to the reactive form. We will consider the following custom validations for this demo.
  • Check for user name availability
  • Password pattern validation
  • Match the password entered in two different fields
Take a look at the application in action.
 
Custom Validation In Angular Reactive Forms
Prerequisites
  • Install Visual Studio code from here
  • Install the latest version of Angular CLI from here
Source Code
 
Get the source code from GitHub.
 

Create the Angular app

 
Navigate to the folder where you want to create your project file. Open a command window and run the command shown below.
  1. ng new angular-forms-validation --routing=false --style=scss  
We are specifying the command to create a new Angular application. The option to create the routing module is set to false and style files extension is set to scss. This command will create the Angular project with name as angular-forms-validation.
 
Change directory to the new project and open the project in VS Code using the set of the command shown below,
  1. cd angular-forms-validation   
  2. code .  

Install Bootstrap

 
Run the following command to install the Bootstrap library.
  1. npm install bootstrap --save  
Add the following import definition in styles.scss file.
  1. @import "~bootstrap/dist/css/bootstrap.css";  

Create the validation service

 
Run the following command to create a new service.
  1. ng g s services\customvalidation  
This command will create a folder named services having two files inside it – customvalidation.service.ts and customvalidation.service.spec.ts. Open the customvalidation.service.ts file and put the following code inside it.
  1. import { Injectable } from '@angular/core';  
  2. import { ValidatorFn, AbstractControl } from '@angular/forms';  
  3. import { FormGroup } from '@angular/forms';  
  4.   
  5. @Injectable({  
  6.   providedIn: 'root'  
  7. })  
  8. export class CustomvalidationService {  
  9.   
  10.   patternValidator(): ValidatorFn {  
  11.     return (control: AbstractControl): { [key: string]: any } => {  
  12.       if (!control.value) {  
  13.         return null;  
  14.       }  
  15.       const regex = new RegExp('^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{8,}$');  
  16.       const valid = regex.test(control.value);  
  17.       return valid ? null : { invalidPassword: true };  
  18.     };  
  19.   }  
  20.   
  21.   MatchPassword(password: string, confirmPassword: string) {  
  22.     return (formGroup: FormGroup) => {  
  23.       const passwordControl = formGroup.controls[password];  
  24.       const confirmPasswordControl = formGroup.controls[confirmPassword];  
  25.   
  26.       if (!passwordControl || !confirmPasswordControl) {  
  27.         return null;  
  28.       }  
  29.   
  30.       if (confirmPasswordControl.errors && !confirmPasswordControl.errors.passwordMismatch) {  
  31.         return null;  
  32.       }  
  33.   
  34.       if (passwordControl.value !== confirmPasswordControl.value) {  
  35.         confirmPasswordControl.setErrors({ passwordMismatch: true });  
  36.       } else {  
  37.         confirmPasswordControl.setErrors(null);  
  38.       }  
  39.     }  
  40.   }  
  41.   
  42.   userNameValidator(userControl: AbstractControl) {  
  43.     return new Promise(resolve => {  
  44.       setTimeout(() => {  
  45.         if (this.validateUserName(userControl.value)) {  
  46.           resolve({ userNameNotAvailable: true });  
  47.         } else {  
  48.           resolve(null);  
  49.         }  
  50.       }, 1000);  
  51.     });  
  52.   }  
  53.   
  54.   validateUserName(userName: string) {  
  55.     const UserList = ['ankit''admin''user''superuser'];  
  56.     return (UserList.indexOf(userName) > -1);  
  57.   }  
  58. }  
The method patternValidator is used to validate the password pattern in our form. The parameter for this method is of type AbstractControl which is a base class for the FormControl. We will use a regular expression to validate the password. We will validate the following four conditions using the regular expression,
  • The password should be a minimum of eight characters long.
  • It has at least one lower case letter.
  • It has at least one upper case letter.
  • It has at least one number.
If the password fails the regex check, we will set the invalidPassword property to true.
 
The method MatchPassword is used to compare the passwords in two fields. This method will accept two parameters of type string. These parameters represent the name of the fields to be matched. We will get the FormControl for these two fields and then match the values in them. If the values do not match, we will set the passwordMismatch property to true.
 
The method userNameValidator is used to verify if the username is already taken or not. This method will accept a parameter of type AbstractControl. We will check if the value of this field is present in a static array, UserList. If the value entered by the user is already present, we will set the userNameNotAvailable property to true. We are using the setTimeout function to invoke this check every two seconds. This will ensure that the error will be thrown after two seconds from the time the user stops typing in the field.
 
Note
For the sake of simplicity of this article, we are using a static array to search for the availability of user names. Ideally, it should be a service call to the server to search the value in a database.
 

Create the reactive form component

 
Run the following command to create the reactive-form component.
  1. ng g c reactive-form  
Open reactive-form.component.ts and put the following code in it.
  1. import { Component, OnInit } from '@angular/core';  
  2. import { Validators, FormGroup, FormBuilder } from '@angular/forms';  
  3. import { CustomvalidationService } from '../services/customvalidation.service';  
  4.   
  5. @Component({  
  6.   selector: 'app-reactive-form',  
  7.   templateUrl: './reactive-form.component.html',  
  8.   styleUrls: ['./reactive-form.component.scss']  
  9. })  
  10. export class ReactiveFormComponent implements OnInit {  
  11.   
  12.   registerForm: FormGroup;  
  13.   submitted = false;  
  14.   
  15.   constructor(  
  16.     private fb: FormBuilder,  
  17.     private customValidator: CustomvalidationService  
  18.   ) { }  
  19.   
  20.   ngOnInit() {  
  21.     this.registerForm = this.fb.group({  
  22.       name: ['', Validators.required],  
  23.       email: ['', [Validators.required, Validators.email]],  
  24.       username: ['', [Validators.required], this.customValidator.userNameValidator.bind(this.customValidator)],  
  25.       password: ['', Validators.compose([Validators.required, this.customValidator.patternValidator()])],  
  26.       confirmPassword: ['', [Validators.required]],  
  27.     },  
  28.       {  
  29.         validator: this.customValidator.MatchPassword('password''confirmPassword'),  
  30.       }  
  31.     );  
  32.   }  
  33.   
  34.   get registerFormControl() {  
  35.     return this.registerForm.controls;  
  36.   }  
  37.   
  38.   onSubmit() {  
  39.     this.submitted = true;  
  40.     if (this.registerForm.valid) {  
  41.       alert('Form Submitted succesfully!!!\n Check the values in browser console.');  
  42.       console.table(this.registerForm.value);  
  43.     }  
  44.   }  
  45. }  
We will create a variable registerForm of type FormGroup. In the ngOnInit method, we will set the controls for the form using the FormBuilder class. All the fields are set as a required field for this form. We will invoke the userNameValidator method of the service using the bind function. For the password field, we will use the compose method to merge in multiple validators into a single function. We will also invoke the MatchPassword method and pass the name of the password and confirmPassword form controls as parameters.
 
The registerFormControl property will return the form controls of the form. The onSubmit method will print the content of the form on the console if the form is valid and submitted successfully.
 
Open reactive-form.component.html and put the following code in it.
  1. <div class="container">    
  2.     <div class="row">    
  3.         <div class="col-md-8 mx-auto">    
  4.             <div class="card">    
  5.                 <div class="card-header">    
  6.                     <h3>Angular Reactive Form</h3>    
  7.                 </div>    
  8.                 <div class="card-body">    
  9.                     <form class="form" [formGroup]="registerForm" (ngSubmit)="onSubmit()">    
  10.                         <div class="form-group">    
  11.                             <label>Name</label>    
  12.                             <input type="text" class="form-control" formControlName="name">    
  13.                             <span class="text-danger"    
  14.                                 *ngIf="(registerFormControl.name.touched || submitted) && registerFormControl.name.errors?.required">    
  15.                                 Name is required    
  16.                             </span>    
  17.                         </div>    
  18.                         <div class="form-group">    
  19.                             <label>Email</label>    
  20.                             <input type="text" class="form-control" formControlName="email">    
  21.                             <span class="text-danger"    
  22.                                 *ngIf="(registerFormControl.email.touched || submitted) && registerFormControl.email.errors?.required">    
  23.                                 Email is required    
  24.                             </span>    
  25.                             <span class="text-danger"    
  26.                                 *ngIf="registerFormControl.email.touched && registerFormControl.email.errors?.email">    
  27.                                 Enter a valid email address    
  28.                             </span>    
  29.                         </div>    
  30.                         <div class="form-group">    
  31.                             <label>User Name</label>    
  32.                             <input type="text" class="form-control" formControlName="username">    
  33.                             <span class="text-danger"    
  34.                                 *ngIf="(registerFormControl.username.touched || submitted) && registerFormControl.username.errors?.required">    
  35.                                 User Name is required    
  36.                             </span>    
  37.                             <span class="text-danger"    
  38.                                 *ngIf="registerFormControl.username.touched && registerFormControl.username.errors?.userNameNotAvailable">    
  39.                                 User Name is not available    
  40.                             </span>    
  41.                         </div>    
  42.                         <div class="form-group">    
  43.                             <label>Password</label>    
  44.                             <input type="password" class="form-control" formControlName="password">    
  45.                             <span class="text-danger"    
  46.                                 *ngIf="(registerFormControl.password.touched || submitted) && registerFormControl.password.errors?.required">    
  47.                                 Password is required    
  48.                             </span>    
  49.                             <span class="text-danger"    
  50.                                 *ngIf="registerFormControl.password.touched && registerFormControl.password.errors?.invalidPassword">    
  51.                                 Password should have minimum 8 characters, at least 1 uppercase letter, 1 lowercase    
  52.                                 letter and 1 number    
  53.                             </span>    
  54.                         </div>    
  55.                         <div class="form-group">    
  56.                             <label>Confirm Password</label>    
  57.                             <input type="password" class="form-control" formControlName="confirmPassword">    
  58.                             <span class="text-danger"    
  59.                                 *ngIf="(registerFormControl.confirmPassword.touched || submitted)&& registerFormControl.confirmPassword.errors?.required">    
  60.                                 Confirm Password is required    
  61.                             </span>    
  62.                             <span class="text-danger"    
  63.                                 *ngIf="registerFormControl.confirmPassword.touched && registerFormControl.confirmPassword.errors?.passwordMismatch">    
  64.                                 Passwords doesnot match    
  65.                             </span>    
  66.                         </div>    
  67.                         <div class="form-group">    
  68.                             <button type="submit" class="btn btn-success">Register</button>    
  69.                         </div>    
  70.                     </form>    
  71.                 </div>    
  72.             </div>    
  73.         </div>    
  74.     </div>    
  75. </div>    
We will create a reactive form and use the Bootstrap card for styling. The card header will contain a title whereas the card body will have the form fields. We will bind the formGroup property of the <form> tag to the name of our form which is registerForm. The onSubmit method will be invoked on submitting the form. We will also bind the formControlName property of each input field to the control name of our FormGroup. We will check for the errors in the form controls and then display the appropriate validation error message on the screen.
 

Create the nav-bar component

 
Run the following command to create the nav-bar component.
  1. ng g c nav-bar  
Open nav-bar.component.html and put the following code in it.
  1. <nav class="navbar navbar-expand-sm navbar-dark bg-dark fixed-top">    
  2.     <a class="navbar-brand" [routerLink]='["/"]'>Form Validation Demo</a>    
  3.     <div class="collapse navbar-collapse">    
  4.         <ul class="navbar-nav mr-auto">    
  5.             <li class="nav-item">    
  6.                 <a class="nav-link" [routerLink]='["/reactive-form"]'>Reactive Form</a>    
  7.             </li>    
  8.         </ul>    
  9.     </div>    
  10. </nav>    
We are adding the navigation link to the reactive form component in the nav bar.
 

Update the app component

 
Open the app.component.html file and put the following code in it.
  1. <app-nav-bar></app-nav-bar>    
  2. <div class="container">    
  3.   <router-outlet></router-outlet>    
  4. </div>    

Update the App module

 
Add the following code in the app.module.ts file. We will import the forms module and define the routing for our application. You can refer to GitHub for the complete source code of this file.
  1. import { RouterModule } from '@angular/router';  
  2. import { ReactiveFormsModule } from  '@angular/forms';  
  3.   
  4. @NgModule({  
  5.   ...      
  6.   imports: [  
  7.     ...  
  8.     ReactiveFormsModule,  
  9.     RouterModule.forRoot([  
  10.       { path: '', component: ReactiveFormComponent },  
  11.       { path: 'reactive-form', component: ReactiveFormComponent }  
  12.     ]),  
  13.   ],  
  14. })  

Execution demo

 
We will use the following command to start the webserver.
  1. ng serve -o  
This command will launch the application in your default browser at http://localhost:4200/. You can perform all the form validations which we have discussed here. This application is also hosted at https://ng-forms-validation.herokuapp.com/. Navigate to the link and play around for a better understanding.
 

Summary

 
We have created a sample user registration form using the reactive form approach in Angular. We have implemented the inbuilt validations as well as custom validations to the form. The Bootstrap library is used to style the form. Get the source code from GitHub and play around for a better understanding.
 
You can also read other articles at my blog
 
See Also