Angular Directive match Password and Confirm password

Read here TOP Angular Interview Questions & Answers
https://www.jsmount.com/angular-interview-question-answers-for-experienced-part-1/


As per Wikipedia —
Angular (commonly referred to as “Angular 2+” or “Angular v2 and is a 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.

Now ANGULAR 8 is on the floor. Thanks to Angular Team !!


In this tutorial we are going to create a Custom Directive to match a PASSWORD & CONFIRM PASSWORD FIELDS. This Code we can use with Angular Version.


A Directive or Custom Directive gives extra power to HTML element. There are three types of directives.

Components: A Directives with templates.
Structural Directives: A Directives that creates and destroys DOM elements.
Structural Directives: A Directives that manipulate DOM by changing behavior and appearance.


So below is a form screen that contains Username, Password & Confirm Password Field.

Create a Custom directive to match password and confirm password

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 below code.

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
directives
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 app.module.ts file & import MatchValueDirective

 import { MatchValueDirective } from './directives/match-value.directive';declarations: [
    AppComponent,
    MatchValueDirective
  ], 

Now run ng serve

Custom directive Angular


YEAH !!!!!! WE ARE DONE.
Thanks for reading…

Read more technical blogs here – https://jsmount.com
https://medium.com/@mohitsaxena2507/angular-7-create-a-directive-to-match-password-and-confirm-password-7112657136aa

Leave a Reply

Your email address will not be published.