Angular Custom directive to match password and confirm password
angular custom directive password validation, angular custom directive, confirm password validation in angular, password and confirm password validation in angular reactive form, password validation in angular, confirm password validation in angular, password match directive angular, angular custom directive for password match
As per Wikipedia —
Angular (commonly referred to as “Angular 2+” or “Angular v2 is TypeScript-based open-source web application framework
led by the Angular Team at Google and by a community of individuals and corporations. Angular is a complete rewrite from the same team that built AngularJS.
In this tutorial, we are going to create a Custom Directive to match a PASSWORD & CONFIRM PASSWORD FIELDS.
Note: This Code we can use with any Angular Version.
A Directive or Custom Directive
gives extra power to the HTML element.
There are three types of directives.
Components:
A Directives with templates.
Attribute Directives
: A Directive that creates and destroys DOM elements.
: Directives that manipulate DOM by changing behavior and appearance.Structural
Directives
Below is a Form screen that contains Username, Password & Confirm Password Fields.

app.component.html file
(we have used here Bootstrap 4 & Template driven form approach)
<div class="container-fluid"> <h2>A Directive for Match Password & Confirm Password</h2> <form #f="ngForm" [matchValue]="['password', 'confirmPassword']"> <div class="form-group"> <label for="username">Username</label> <input type="text" name="username" placeholder="enter your username" class="form-control" [(ngModel)]="model.username" #username="ngModel" [class.is-invalid]="f.submitted && username.invalid" [class.is-valid]="username.valid" required> <div class="invalid-feedback">Please fill out this field</div> <div class="valid-feedback">Username is available</div> </div> <div class="form-group"> <label for="password">Password</label> <input type="password" class="form-control" [(ngModel)]="model.password" #password="ngModel" name="password" placeholder="enter your password" [class.is-invalid]="f.submitted && password.invalid" required minlength="6"> <div *ngIf="f.submitted && password.invalid" class="invalid-feedback"> <div *ngIf="password.errors.required">Password is required</div> <div *ngIf="password.errors.minlength">Password must be at least 6 characters</div> </div> </div> <div class="form-group"> <label for="confirmPassword">Confirm Password</label> <input type="password" class="form-control" [(ngModel)]="model.confirmPassword" #confirmPassword="ngModel" name="confirmPassword" placeholder="enter your confirm password" [class.is-invalid]="f.submitted && confirmPassword.invalid" required> <div *ngIf="f.submitted && confirmPassword.invalid" class="invalid-feedback"> <div *ngIf="confirmPassword.errors.required">Confirm Password is required</div> <div *ngIf="confirmPassword.errors.matchValueError">Confirm Password & Password must be same.</div> </div> </div><button type="submit" class="btn btn-primary" (click)="onSubmit(f)">Submit</button> </form> </div>
[matchValue]= “[‘password’, ‘confirmPassword’]”
This is a directive selector which we have created in the above code & applied on Form.
app.component.ts file
( Code of Typescript file. )
import { Component } from "@angular/core"; @Component({ selector: "app-root", templateUrl: "./app.component.html", styleUrls: ["./app.component.scss"] }) export class AppComponent { title = "Angular 7 Match password & Confirm Password"; model: any = {}; onSubmit(userForm) { if (userForm.form.valid) { alert("Form submitted sucessfully"); } } }
Now Let’s create a directive folder and inside that create a file named
ng g directives/match-value.directive
match-value.directive.ts

import { Directive, Input } from "@angular/core"; import { Validator, ValidationErrors, FormGroup, NG_VALIDATORS } from "@angular/forms"; import { MatchValue } from "./match-value.validator"; @Directive({ selector: "[matchValue]", providers: [ { provide: NG_VALIDATORS, useExisting: MatchValueDirective, multi: true } ] }) export class MatchValueDirective implements Validator { @Input("matchValue") matchValueFields: string[] = []; constructor() {} validate(formGroup: FormGroup): ValidationErrors { return MatchValue(this.matchValueFields[0], this.matchValueFields[1])( formGroup ); } }
Create a new file within the same folder named match-value.validator.ts
import { FormGroup } from "@angular/forms";
// custom validator to check that two fields match
export function MatchValue(
firstControlName: string,
secondControlName: string
) {
return (formGroup: FormGroup) => {
const firstControl = formGroup.controls[firstControlName];
const secondControl = formGroup.controls[secondControlName];
// return null if controls haven't initialised yet
if (
!firstControl ||
!secondControl ||
!firstControl.value ||
!secondControl.value
) {
return null;
}
if (secondControl.errors && !secondControl.errors.matchValueError) {
return null;
}
if (firstControl.value !== secondControl.value) {
secondControl.setErrors({ matchValueError: true });
} else {
secondControl.setErrors(null);
}
};
}
💡Now let’s modify the app.module.ts file & import MatchValueDirective.
import { MatchValueDirective } from './directives/match-value.directive';declarations: [
AppComponent,
MatchValueDirective
],
Now run ng serve

YEAH !!!!!! WE ARE DONE.
Thanks for reading.
angular custom directive password validation, angular custom directive, confirm password validation in angular, password and confirm password validation in angular reactive form, password validation in angular, confirm password validation in angular, password match directive angular, angular custom directive for password match
- Angular Interview Questions & Answers 2021 – Part 3 – JS Mount
- Why Angular is a Preferred Choice for Developers? Top Features
- Angular Interview Questions & Answers You should know Part 2
- Web Application Security Best Practices | Top Tips to Secure Angular App
- NgRx Top Interview Questions and Answers You should know
- Tips to Boost Angular App Performance | Web page Speed Optimization
- Angular NgModule, AOT, and DI, and EntryComponents with example
- Angular Dependency Injection Provider and Types of Provider
- Rx JS Top Operators with examples | Rx JS interview questions
- What’s new in Angular 9 | Top updates in Angular 9 By JS mount
- What’s new in Angular 8 | Angular 8 Latest Feature By JS mount
- Prime NG Row Group with Subheader and Totals Row
- How to implement Reactive Form with Prime NG table
- Angular Unit Testing Spy, Router, Fake Async, tick, & Subscribe
- Angular Auto Tab Directive : Auto focus on next field
- VS Code Useful Extensions for Web Development
- Angular HTTP Request Testing with HttpClientTestingModule & HttpTestingController
- Dynamic Tooltip with Angular Pipe: Performance Orientation
- Best Practices for Writing Angular Apps | Angular Guidelines
- Angular Interview Question & Answers for Experienced – Part 1
- Angular Custom directive to match password and confirm password
David
I was searching same to create a custom directive for password match, finally I found, Thanks JS Mount.