DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Enhancing Angular Directives: Implementing Permission-Based Conditional Rendering With Else Case
  • 50+ Top Angular Interview Questions and Answers
  • Rediscovering Angular: Modern Advantages and Technical Stack
  • Angular Input/Output Signals: The New Component Communication

Trending

  • Event-Driven Architectures: Designing Scalable and Resilient Cloud Solutions
  • Power BI Embedded Analytics — Part 2: Power BI Embedded Overview
  • What Is Plagiarism? How to Avoid It and Cite Sources
  • Docker Model Runner: Streamlining AI Deployment for Developers
  1. DZone
  2. Coding
  3. Frameworks
  4. Implement Shared Custom Validator Directive in Angular

Implement Shared Custom Validator Directive in Angular

Ever gotten that annoying but useful message, 'Passwords don't match,' while trying to log in somewhere? In this post, we learn how to make that mechanism with Angular.

By 
Sibeesh Venu user avatar
Sibeesh Venu
·
Nov. 08, 18 · Tutorial
Likes (18)
Comment
Save
Tweet
Share
22.3K Views

Join the DZone community and get the full member experience.

Join For Free

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 confirm the password, remember? Here we are going to look into that. At the end of this article, you will get to know how to create a new shared directive according to the requirements of your app. This post is a continuation of the 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.

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

You can always clone or download the source code here.

Background

Validations have a vital role in all application no matter in what language it is being 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, 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 code 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.

import { Validator, AbstractControl, NG_VALIDATORS } from "@angular/forms";
import { Directive, Input } from "@angular/core";

Now Let's define our class and @Directive.

import { Validator, AbstractControl, NG_VALIDATORS } from "@angular/forms";
import { Directive, Input } from "@angular/core";

@Directive({
    selector: "[appEqualValidator]",
    providers: [{
        provide: NG_VALIDATORS,
        useExisting: EqualValidatorDirective,
        multi: true
    }]
})
export class EqualValidatorDirective implements Validator {
    validate(c: AbstractControl): { [key: string]: any; } {
        throw new Error("Method not implemented.");
    }
    registerOnValidatorChange?(fn: () => void): void {
        throw new Error("Method not implemented.");
    }
}

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 tp tje app.module.ts file.

import { BrowserModule } from '@angular/platform-browser';
import { BrowserAnimationsModule} from '@angular/platform-browser/animations'
import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { MatButtonModule, MatCardModule, MatInputModule, MatSnackBarModule, MatToolbarModule } from '@angular/material';
import { FormsModule, ReactiveFormsModule } from '@angular/forms'
import { EqualValidatorDirective } from './shared/equal.validator.directive';

import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { NavComponent } from './nav/nav.component';
import { RegistrationComponent } from './registration/registration.component';
import { LoginComponent } from './login/login.component';

import { AuthService } from './auth.service';
import { AuthGuard } from './auth.guard';

const myRoots: Routes = [
  { path: '', component: HomeComponent, pathMatch: 'full' , canActivate: [AuthGuard]},
  { path: 'register', component: RegistrationComponent },
  { path: 'login', component: LoginComponent},
  { path: 'home', component: HomeComponent, canActivate: [AuthGuard]}
];

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    NavComponent,
    RegistrationComponent,
    LoginComponent,
    EqualValidatorDirective
  ],
  imports: [
    BrowserModule, BrowserAnimationsModule, FormsModule, ReactiveFormsModule,
    MatButtonModule, MatCardModule, MatInputModule, MatSnackBarModule, MatToolbarModule,
    RouterModule.forRoot(myRoots)
  ],
  providers: [AuthService, AuthGuard],
  bootstrap: [AppComponent]
})
export class AppModule { }

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 our validator. So we are going to change our markup for the confirm password field as shown below.

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

export class EqualValidatorDirective implements Validator {
    @Input() appEqualValidator: string;
    validate(c: AbstractControl): { [key: string]: any; } {
        const controlToCompare = c.parent.get(this.appEqualValidator)
        if (controlToCompare && controlToCompare.value == c.value)return { "equal": true };
        return { "notEqual": true }
    }
    registerOnValidatorChange?(fn: () => void): void {
        throw new Error("Method not implemented.");
    }
}

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}. 

Introduce New Span for Custom Message

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

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

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

Here we have seen how we can implement shared custom validator directive.

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

Directive (programming) AngularJS

Published at DZone with permission of Sibeesh Venu, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Enhancing Angular Directives: Implementing Permission-Based Conditional Rendering With Else Case
  • 50+ Top Angular Interview Questions and Answers
  • Rediscovering Angular: Modern Advantages and Technical Stack
  • Angular Input/Output Signals: The New Component Communication

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!