Implement Shared Custom Validator Directive In Angular

Introduction

In this post, we are going to see how to create a custom validator directive in Angular 5. We have already seen how to do validation in our previous posts, and we have not done any validations for comparing the password and confirming the password, remember? Here, we are going to see that. At the end of this article, you will get to know how to create a new shared directive according to our requirements. This post is a continuation of the course Developing an Angular 5 App series if you haven’t gone through the previous posts yet, I strongly recommend you to do that. You can find the links to the previous posts below. I hope you will like this article. You can always see this article on my blog here.

Developing an Angular 5 App series

These are the previous posts in this series. Please go ahead and have a look.

  1. What Is New and How to Set Up our First Angular 5 Application
  2. Angular 5 Basic Demo Project Overview
  3. Generating Your First Components And Modules in Angular 5 App
  4. Implement Validations in Angular 5 App
  5. Validation Using Template Driven Forms in Angular 5

Source Code

You can always clone or download the source code here.

Background

Validations have a vital role in all applications no matter in what language it is been developed. And since it is an essential part, there are many ways to achieve it. If we create a custom shared directive for creating a compare validator, it would be a great piece of code right, which can be reused.

Using the code

It is recommended to clone the project from GitHub so that you can try everything on your own. Let’s go ahead and write some codes now.

Creating a custom directive

Let’s just create a new directive in a shared folder and name it equal.validator.directive.ts. Now open that file and start writing the code. Let’s import some of the core components first.

  1. import {  
  2.     Validator,  
  3.     AbstractControl,  
  4.     NG_VALIDATORS  
  5. } from "@angular/forms";  
  6. import {  
  7.     Directive,  
  8.     Input  
  9. } from "@angular/core";  

Now, let’s define our class and @Directive.

  1. import {  
  2.     Validator,  
  3.     AbstractControl,  
  4.     NG_VALIDATORS  
  5. } from "@angular/forms";  
  6. import {  
  7.     Directive,  
  8.     Input  
  9. } from "@angular/core";  
  10. @Directive({  
  11.     selector: "[appEqualValidator]",  
  12.     providers: [{  
  13.         provide: NG_VALIDATORS,  
  14.         useExisting: EqualValidatorDirective,  
  15.         multi: true  
  16.     }]  
  17. }) export class EqualValidatorDirective implements Validator {  
  18.     validate(c: AbstractControl): {  
  19.         [key: string]: any;  
  20.     } {  
  21.         throw new Error("Method not implemented.");  
  22.     }  
  23.     registerOnValidatorChange ? (fn: () => void) : void {  
  24.         throw new Error("Method not implemented.");  
  25.     }  
  26. }  

As you can see we are actually inheriting our new class EqualValidatorDirective from Validator. Now, we need to change the implementations of the method inside it. We should also add our new directive in app.module.ts file.

  1. import {  
  2.     BrowserModule  
  3. } from '@angular/platform-browser';  
  4. import {  
  5.     BrowserAnimationsModule  
  6. } from '@angular/platform-browser/animations'  
  7. import {  
  8.     NgModule  
  9. } from '@angular/core';  
  10. import {  
  11.     RouterModule,  
  12.     Routes  
  13. } from '@angular/router';  
  14. import {  
  15.     MatButtonModule,  
  16.     MatCardModule,  
  17.     MatInputModule,  
  18.     MatSnackBarModule,  
  19.     MatToolbarModule  
  20. } from '@angular/material';  
  21. import {  
  22.     FormsModule,  
  23.     ReactiveFormsModule  
  24. } from '@angular/forms'  
  25. import {  
  26.     EqualValidatorDirective  
  27. } from './shared/equal.validator.directive';  
  28. import {  
  29.     AppComponent  
  30. } from './app.component';  
  31. import {  
  32.     HomeComponent  
  33. } from './home/home.component';  
  34. import {  
  35.     NavComponent  
  36. } from './nav/nav.component';  
  37. import {  
  38.     RegistrationComponent  
  39. } from './registration/registration.component';  
  40. import {  
  41.     LoginComponent  
  42. } from './login/login.component';  
  43. import {  
  44.     AuthService  
  45. } from './auth.service';  
  46. import {  
  47.     AuthGuard  
  48. } from './auth.guard';  
  49. const myRoots: Routes = [{  
  50.     path: '',  
  51.     component: HomeComponent,  
  52.     pathMatch: 'full',  
  53.     canActivate: [AuthGuard]  
  54. }, {  
  55.     path: 'register',  
  56.     component: RegistrationComponent  
  57. }, {  
  58.     path: 'login',  
  59.     component: LoginComponent  
  60. }, {  
  61.     path: 'home',  
  62.     component: HomeComponent,  
  63.     canActivate: [AuthGuard]  
  64. }];  
  65. @NgModule({  
  66.     declarations: [AppComponent, HomeComponent, NavComponent, RegistrationComponent, LoginComponent, EqualValidatorDirective],  
  67.     imports: [BrowserModule, BrowserAnimationsModule, FormsModule, ReactiveFormsModule, MatButtonModule, MatCardModule, MatInputModule, MatSnackBarModule, MatToolbarModule, RouterModule.forRoot(myRoots)],  
  68.     providers: [AuthService, AuthGuard],  
  69.     bootstrap: [AppComponent]  
  70. }) export class AppModule {}  

Implement validate

Before we do that, we should add our new custom directive selector in our confirm password field, because that’s where we are going to use in our validator. So, we are going to change our markup for confirming password field as below.

  1. <div class="form-group" [class.has-error]="confirmPasswordControl.invalid && confirmPasswordControl.touched" [class.has-success]="confirmPasswordControl.valid">   
  2.   <input type="password" required class="form-control" name="confirmPassword" appEqualValidator="password" placeholder="Confirm Password" [(ngModel)]="confirmPassword" #confirmPasswordControl="ngModel">   
  3.     <span class="help-block" *ngIf="confirmPasswordControl.errors?.required && confirmPasswordControl.touched"> Confirm password is required </span>   
  4. </div>  

As you can see, we are using the selector appEqualValidator=”password” in our confirm password field. Please do check my previous posts if you are not sure how to implement other validations like email and required.

Now, let’s go back to our custom directive and make some changes.

  1. export class EqualValidatorDirective implements Validator {  
  2.     @Input() appEqualValidator: string;  
  3.     validate(c: AbstractControl): {  
  4.         [key: string]: any;  
  5.     } {  
  6.         const controlToCompare = c.parent.get(this.appEqualValidator) if (controlToCompare && controlToCompare.value == c.value) return {  
  7.             "equal"true  
  8.         };  
  9.         return {  
  10.             "notEqual"true  
  11.         }  
  12.     }  
  13.     registerOnValidatorChange ? (fn: () => void) : void {  
  14.         throw new Error("Method not implemented.");  
  15.     }  
  16. }  

Here, we get our confirmPassword control in the absolute control “c”, and in the next line, we are just finding our password control by getting the parent element of confirmPassword. Once we get that, we can easily perform the comparison easily right? So, if it matches, we return { “equal”: true }; or else { “notEqual”: true }. Sounds good?

Introduce new span for custom message

Now, we have a custom validator which compares two values, and the only thing which is pending is to create a span for showing our new message in UI. Let’s change our markup now.

  1. <div class="form-group" [class.has-error]="confirmPasswordControl.invalid && confirmPasswordControl.touched" [class.has-success]="confirmPasswordControl.valid">  
  2.   <input type="password" required class="form-control" name="confirmPassword" appEqualValidator="password" placeholder="Confirm Password" [(ngModel)]="confirmPassword" #confirmPasswordControl="ngModel">   
  3.     <span class="help-block" *ngIf="confirmPasswordControl.errors?.required && confirmPasswordControl.touched"> Confirm password is required </span>   
  4.       <span class="help-block" *ngIf="confirmPasswordControl.errors?.notEqual && confirmPasswordControl.touched && !confirmPasswordControl.errors?.required"> Password doesn't match </span>   
  5. </div>  

As you can see, we are showing the custom message only if the directive returns notEqual property and there are no required errors. Let’s run our application and see it in action.

Angular

Here, we have seen how we can implement shared custom validator directive. Let’s connect to a database and save these values in next article. 

Conclusion

Thanks a lot for reading. Did I miss anything that you may think is needed? Did you find this post useful? I hope you liked this article. Please share your valuable suggestions and feedback.

Your turn. What do you think?

A blog isn’t a blog without comments, but do try to stay on topic. If you have a question unrelated to this post, you’re better off posting it on C# Corner, Code Project, Stack Overflow, Asp.Net Forum instead of commenting here. Tweet or email me a link to your question there and I’ll definitely try to help if I can.


Similar Articles