Home > Software engineering >  How to create custom Validator for password and confirm password in angular
How to create custom Validator for password and confirm password in angular

Time:09-16

I am trying to add custom validation in angular for password and confirm password :

<div >
  <label  for="password">Password</label>
  <input type="password" id="password" name="password" 
         [class.is-invalid]="form['password'].invalid && form['password'].touched" formControlName="password"
         placeholder="Enter Password">
  <div *ngIf="form['password'].touched && form['password'].invalid" >
    <small *ngIf="form['password'].errors?.['required']">Password is Required</small>
    <small *ngIf="form['password'].errors?.['minlength']">Password must be at least 5 Characters</small>
  </div>
</div>
<div >
  <label  for="confirmPassword">Confirm Password</label>
  <input type="password" id="confirmPassword" name="confirmPassword" 
         [class.is-invalid]="form['confirmPassword'].errors && form['confirmPassword'].touched"
         formControlName="confirmPassword" placeholder="Enter Confirm Password">
  <div *ngIf="form['confirmPassword'].errors && form['confirmPassword'].touched" >
    <small *ngIf="form['confirmPassword'].errors['required']">Confirm Password is Required</small>
    <small *ngIf="form['confirmPassword'].errors['matching']">Passwords do not match</small>
  </div>
</div>

CodePudding user response:

You can create custom validation for password and confirm password like this :

//password.validator.ts

import { AbstractControl, FormGroup, ValidatorFn } from "@angular/forms";

export default class Validation {
  static match(controlName: string, checkControlName: string): ValidatorFn {
    return (controls: AbstractControl) => {
      const control = controls.get(controlName);
      const checkControl = controls.get(checkControlName);

      if (checkControl?.errors && !checkControl.errors['matching']) {
        return null;
      }

      if (control?.value !== checkControl?.value) {
        controls.get(checkControlName)?.setErrors({ matching: true });
        return { matching: true };
      } else {
        return null;
      }
    };
  }
}

then add that validation

//register.component.ts
import Validation from './password.validator';
this.registerForm = this.fb.group({
      password: ['', [Validators.required, Validators.minLength(5)]],
      confirmPassword: ['', Validators.required]
    }, { validators: [Validation.match('password', 'confirmPassword')] } )

to your .ts file after the formgroup like this and use it the way you have mentioned

  • Related