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.
Structural Directives: Directives that manipulate DOM by changing behavior and appearance.


Below is a Form screen that contains Username, Password & Confirm Password Fields.

angular custom directive password validation
angular custom directive password validation

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
match-value.directive.ts

ng g directives/match-value.directive
angular custom directive password validation
File structure
 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

angular custom directive password validation
angular custom directive password validation


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


Leave a Reply

Your email address will not be published.