In Angular 5 doesn’t support inbuilt validation process for confirm password functionality. For this we have to create our own custom validator code.
Step 1. Create the confirm-equal-validator.directive.ts file then write the code like this
import { Validator, NG_VALIDATORS, AbstractControl } from "@angular/forms"; import { Directive } from "@angular/core"; @Directive({ selector:'[appConfirmEqualValidator]', providers:[{ provide: NG_VALIDATORS, useExisting: ConfirmEqualValidatorDirective, multi: true }] }) export class ConfirmEqualValidatorDirective implements Validator { validate(passwordGroup: AbstractControl): { [key: string]: any } | null { const passwordField = passwordGroup.get('password'); const confirmPasswordField = passwordGroup.get('confirmPassword'); if (passwordField && confirmPasswordField && passwordField.value !== confirmPasswordField.value) { return { 'notEqual': true }; } return null; } }
Step 2: Go to the HTML page implement the code like this
<div ngModelGroup="passwordGroup" #passwordGroup="ngModelGroup" appConfirmEqualValidator [class.has-error]="passwordGroup.errors?.notEqual && !confirmPassword.errors?.required"> <div class="form-group" [class.has-error]="password.touched && password.invalid"> <label for="password" class="control-label">Password</label> <input name="password" required type="text" class="form-control" [(ngModel)]="employee.password" #password="ngModel"> <span class="help-block" *ngIf="password.touched && password.errors?.required"> Password is required </span> </div> <div class="form-group" [class.has-error]="confirmPassword.touched && confirmPassword.invalid"> <label for="confirmPassword" class="control-label">Confirm Password</label> <input name="confirmPassword" required type="text" class="form-control" [(ngModel)]="employee.confirmPassword" #confirmPassword="ngModel"> <span class="help-block" *ngIf="confirmPassword.touched && confirmPassword.errors?.required"> Confirm Password is required </span> <span class="help-block" *ngIf="confirmPassword.touched && passwordGroup.errors?.notEqual && !confirmPassword.errors?.required"> Password and Confirm Password does not match </span> </div> </div>
In the above code we show that NgModelGroup Directive use to create a sub-group within a form and it is useful to validate a sub-group of elements on the form.
Step 3: Go to the app.module.ts file import the code like this
import {ConfirmEqualValidatorDirective } from ‘./shared/confirm-equal-validator.directive’;
and in @NgModule({
ConfirmEqualValidatorDirective
})