Creating a Password Match Validator in Angular: A Step-by-Step Guide to Cross-Controls Validations

Posted by

Step by Step Creating Password Match Validator in Angular

Step by Step Creating Password Match Validator in Angular | Cross Controls Validations in Angular

Angular provides a powerful feature called cross control validations that allow us to validate multiple form fields against each other. In this article, we will go through the step by step process of creating a password match validator in Angular.

Step 1: Create a new Angular project

First, we need to create a new Angular project using the Angular CLI. Open a terminal and run the following command:

ng new password-match-validator

This will create a new Angular project with the name ‘password-match-validator’.

Step 2: Create a new component for the password match validator

Next, we need to create a new component for the password match validator. In the terminal, run the following command:

ng generate component password-match-validator

This will create a new component with the name ‘password-match-validator’.

Step 3: Implement the password match validator logic

Open the HTML file of the ‘password-match-validator’ component and add the following code:

        <form [formGroup]="passwordForm">
            <input type="password" formControlName="password" placeholder="Enter password">
            <input type="password" formControlName="confirmPassword" placeholder="Confirm password">
        </form>
    

Next, open the TypeScript file of the ‘password-match-validator’ component and add the following code:

        import { Component, OnInit } from '@angular/core';
        import { FormGroup, FormBuilder, Validators } from '@angular/forms';

        @Component({
            selector: 'app-password-match-validator',
            templateUrl: './password-match-validator.component.html',
            styleUrls: ['./password-match-validator.component.css']
        })
        export class PasswordMatchValidatorComponent implements OnInit {
            passwordForm: FormGroup;

            constructor(private formBuilder: FormBuilder) { }

            ngOnInit(): void {
                this.passwordForm = this.formBuilder.group({
                    password: ['', Validators.required],
                    confirmPassword: ['', Validators.required]
                }, { validators: this.passwordMatchValidator });
            }

            passwordMatchValidator(formGroup: FormGroup) {
                return formGroup.get('password').value === formGroup.get('confirmPassword').value ? null : { mismatch: true };
            }
        }
    

Step 4: Use the password match validator in a form

Finally, we can use the password match validator in a form by referencing the ‘passwordForm’ in the HTML template of another component:

        <app-password-match-validator></app-password-match-validator>
        <div *ngIf="passwordForm.hasError('mismatch')">
            Passwords do not match
        </div>
    

That’s it! Now you have successfully created a password match validator in Angular using cross control validations. You can now use this validator in any form to ensure that the password and confirm password fields match.

0 0 votes
Article Rating
11 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@schcarlos18
6 months ago

Thanks

@user-fs6uh3qj8b
6 months ago

Great tutorial. Thanks

@codersexpo1580
6 months ago

Thanks for this! Just a note to build on your effort here. If you want to pass parameters to your custom validator function you can do it like so:

import { AbstractControl, ControlContainer, ValidationErrors, ValidatorFn } from "@angular/forms";

export function checkvaluesmatch(val1: any, val2: any): ValidatorFn {

return (control: AbstractControl): ValidationErrors | null => {

let v1 = control.get(val1);

let v2 = control.get(val2);

if (v1 && v2 && v1?.value != v2?.value) {

return {

valuematcherror: true

}

}

return null;

}

}

This way you are not tied to using the key words 'password' and 'confirmpassword'. This is a more abstract approach. Then just call it like..
….{ validators: checkvaluesmatch('password', 'confirmpassword') });

@edwedw123
6 months ago

thanks for the video but mat-error doesnt work with this validations

@Latipov21
6 months ago

That's great! Thank you so much for the tutorial. Short and beautiful!

@brindamessu9978
6 months ago

thank you very much

@user-mi9gw5vj7y
6 months ago

Thank you very much! you've been incredibly helpful to me!

@rafaelarolim2320
6 months ago

Awesome, thanks!

@VuMinh-dr3cm
6 months ago

niceeee thanks so much

@muralim8175
6 months ago

Hi @dhanjay kumar, recently wateched your very nice, my one suggestion is, am a begginer to start angular , can you re- arrange the begginer level & intermediate level in your playlist, and also you created batch 4 in playlist it's okay with start that beginner level

@jayshankarbehera5934
6 months ago

Nice