Validating Passwords with Angular Reactive Forms

Ole Ersoy
1 min readJan 29, 2022

--

Image by R_Winkelmann from Pixabay

Updated Version

There’s an updated version of this article here:

Scenario

On our registration form we have a password field and a confirmPassword field.

We want to validate that the confirmPassword field matches the password field prior to enabling the submit button for the form.

If the passwords do not match then the mat-error notification below the confirmPassword field will display a message indicating this.

Approach

Matching the Passwords

First within our validation.service.ts service we will create a factory function used to produce the ValidatorFn instance that will check whether the passwords match.

If the there are no errors then null is returned. If the passwords do no match we set the passwordMismatch error on the confirmPasswordControl .

Creating the Reactive Form

Note that the passwordMatch function is passed in as the second argument in the FormGroup constructor:

Creating the Reactive Form Template

Demo

--

--