Angular: Confirm Password Validation Custom Validator

Jonathan Gamble - Oct 24 '21 - - Dev Community

Note: You need a basic understand of Angular reactive forms for this.

There is not a custom validator in Angular for confirm passwords, so I found one here. I don't want to have to rewrite the code in my component, so here is my version that just 'works' out of the box.

Create a file called form-validators.ts with this:

export function matchValidator(
  matchTo: string, 
  reverse?: boolean
): ValidatorFn {
  return (control: AbstractControl): 
  ValidationErrors | null => {
    if (control.parent && reverse) {
      const c = (control.parent?.controls as any)[matchTo] 
        as AbstractControl;
      if (c) {
        c.updateValueAndValidity();
      }
      return null;
    }
    return !!control.parent &&
      !!control.parent.value &&
      control.value === 
      (control.parent?.controls as any)[matchTo].value
      ? null
      : { matching: true };
  };
}
Enter fullscreen mode Exit fullscreen mode

Then, in your formgroup, add your validators like so (note: the other validators are optional):

password: ['', [
  Validators.required,
  Validators.pattern('^(?=.*[0-9])(?=.*[a-zA-Z])([a-zA-Z0-9]+)$'),
  Validators.minLength(6),
  Validators.maxLength(25),
  matchValidator('confirmPassword', true)
]],
confirmPassword: ['', [
  Validators.required,
  matchValidator('password')
]],
Enter fullscreen mode Exit fullscreen mode

Notice the matchValidator uses the true input to see if it is the reverse node. This means, put true on the item that needs to be checked, and don't put true where you want the error message to display. So in this case, the error message is only displayed on the confirmPassword field, while it is checked on the password field as well.

The error code will be matching, so you can use this in your mat-form-field input:

<mat-error *ngIf="confirmPassword.hasError('matching')">
Password must match.
</mat-error>
Enter fullscreen mode Exit fullscreen mode

Note: If you want the form to update immediately while typing, you can use a custom errorStateMatcher.

Now, you can reuse the matching validator across your app without writing custom functions.

If you enjoy these articles, give me a thumbs up here and on stackoverflow, as I use these points to debug my applications.

Thanks,

J

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .