DEV Community

Cover image for Angular: Confirm Password Validation Custom Validator
Jonathan Gamble
Jonathan Gamble

Posted on

10

Angular: Confirm Password Validation Custom Validator

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

Billboard image

Imagine monitoring that's actually built for developers

Join Vercel, CrowdStrike, and thousands of other teams that trust Checkly to streamline monitor creation and configuration with Monitoring as Code.

Start Monitoring

Top comments (0)

Heroku

This site is powered by Heroku

Heroku was created by developers, for developers. Get started today and find out why Heroku has been the platform of choice for brands like DEV for over a decade.

Sign Up

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay