Match Password Validation Tutorial in Angular 5

Why match password validation is essential?

Every registration form nowadays require match password validation. This let the user to re-enter a valid password to avoid any possible input mistake. While it was very straightforward in AngularJS to address this requirement by using ‘ng-model’, it’s a bit tricky in Angular, but I consider it as a much better approach then its predecessor.

For the purpose of this article, we will be creating a form with Reactive approach. You can learn more about custom validation in Angular in this article. I assume that you have already assembled an Angular application, so we will dive right into the core.

So let us start by creating a registration component to encapsulate our logic and the form’s UI. I have created a minimal UI with some input elements. Let’s have a look at the it.

So this is how our UI looks in the browser, let us have a look at its code.

In the above code, we have a form with few elements. We have assigned the formGroup attribute to our form to have a reference of it in the component. You could also see that I have wrapped the password and repeat password section into another formGroup. This is because we need the context of ‘password’ element while validating ‘repeat password’. Other than this, we have added ‘required’ validation to every elements and a custom validation to ‘repeat password’ element. So, this is our validation which will get triggered when the password does not match.

Let’s now peek into the component to understand how to wire up the validation triggers.

You could see that we have created two member variables viz, registrationFormGroup & passwordFormGroup in our component. In the constructor, we have initialised the password form group and added our custom validator on form group level. Finally we have initialised our parent registration form group and added the reference of inner password form group.

Finally, let’s have a look at our logic of custom validator.

As we have the reference of our inner password form group, I took the value of its controls and compared their equality. So, we are done with the coding, let us run the application and see if the validation works.

Match Password Validation Demo

Voila!, it works just as we expected. I hope this article will help you to add match password validation in your forms. If you have any query then please write in down in the comment section.

It takes lots of time and efforts to create these articles, if you find it interesting, please share it with your friends.