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

Top comments (0)

Jetbrains image

Is Your CI/CD Server a Prime Target for Attack?

57% of organizations have suffered from a security incident related to DevOps toolchain exposures. It makes sense—CI/CD servers have access to source code, a highly valuable asset. Is yours secure? Check out nine practical tips to protect your CI/CD.

Learn more

👋 Kindness is contagious

Engage with a wealth of insights in this thoughtful article, valued within the supportive DEV Community. Coders of every background are welcome to join in and add to our collective wisdom.

A sincere "thank you" often brightens someone’s day. Share your gratitude in the comments below!

On DEV, the act of sharing knowledge eases our journey and fortifies our community ties. Found value in this? A quick thank you to the author can make a significant impact.

Okay