Monday, November 11, 2019

Create Confirm Password Validation using Custom Validator with Angular 7|8|9

Angular Validators class offers some useful validators like pattern required, minLength and maxLength. However, sometimes we require to use validate some complex values. In this type of condition, custom validators angular are very useful.
Create Confirm Password Validation using Custom Validator with Angular

Reactive Forms in Angular lets us define custom validators very easily. In this tutorial, I am going to create confirm password validation. To do that I will be creating a separate folder by the name of must-match and keep my custom validator file there. I will name it validate-password angular .ts so it will sound generic.
must-match > validate-password.ts
import { AbstractControl } from '@angular/forms';
export class ValidatePassword {
  static MatchPassword(abstractControl: AbstractControl) {
    let password = abstractControl.get('password').value;
    let confirmPassword = abstractControl.get('confirmPassword').value;
     if (password != confirmPassword) {
         abstractControl.get('confirmPassword').setErrors({
           MatchPassword: true
         })
    } else {
      return null
    }
  }
 
}

Using the Custom Validator in Reactive Form
import { FormBuilder Validators } from "@angular/forms";
import { ValidatePassword } from "./must-match/validate-password";
@Component({
  //...
})
export class AppComponent {
   registrationForm = this.fb.group({
     PasswordValidation: this.fb.group({
        password: ['', Validators.required],
        confirmPassword: ['', Validators.required]
     },{
        validator: ValidatePassword.MatchPassword // custom validation
     })
   })
}

3 comments: