Match Password Validation in Angular Reactive Forms



Angular Password Validation Using Custom Validator

Custom Validator To Match Password and Confirm Password in Angular Reactive Forms


In this blog post, we'll learn how to create a custom validator to match password and confirm password.

In Angular, there is no built-in validator for matching password and confirm password.

So we are going to create new custom validator in angular to match password and confirm password. Read more about Custom validators in angular 


Reactive Form Setup


Now, We'll create registration form as following.

As we are creating validator for reactive form, we should have reactive form setup. If you are new to angular reactive forms, I would recommend reading this article: Angular Reactive Forms

To get the better understanding we are going to create one reactive form page and we'll apply custom validators to it.

We'll be using the following files throughout this example:

  • registration-form.component.html
  • registration-form.component.ts

To user reactive form, we need to import ReactiveFormsModule.
app.module.ts will look as follows:

import { ReactiveFormsModule } from '@angular/forms';

@NgModule({
  imports: [
    // other imports ...
    ReactiveFormsModule
  ],
})
export class AppModule { }



Generate a form using Angular form builder

The registration-form.component.ts will look as follows, It doesn't contain any custom validators right now, but we'll add it later.


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

@Component({
  selector: 'app-registration-form',
  templateUrl: './app-registration-form.component.html',
  styleUrls: ['./app-registration-form.component.scss'],
})

export class RegistrationFormComponent implements OnInit {
  registerForm: FormGroup;
  submitted:boolean=false;

  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.registerForm = this.fb.group({
      email: ['']
      password:[''],
      confirmPasswod:['']
    });
  }
  
  onSubmit() {
    this.submitted=true;
   }
}


Assign formGroup and formControlName to control

Now the template file registration-form.component.html will look as follows

<form [formGroup]="registerForm" novalidate>
  Email:
  <input type="text" formControlName="email">
  Password:
  <input type="password" formControlName="password">
  Confirm Password:
  <input type="password" formControlName="confirmPassword">
</form>

Create Custom Validator

Now create new file called confirm-password.validator.ts and the following code.

import {AbstractControl} from '@angular/forms';

export class ConfirmPasswordValidator {
    static MatchPassword(control: AbstractControl) {
       let password = control.get('password').value;

       let confirmPassword = control.get('confirmPassword').value;

        if(password != confirmPassword) {
            control.get('confirmPassword').setErrors( {ConfirmPassword: true} );
        } else {
            return null
        }
    }
}

The above code is to validate password and confirm password.

As you can see that we got the value of password and confirm password and compared both values.

If both values are not the same, that means didn't match the password, so we'll set error using angular setErrors function. and if both are same then we'll return null.

Now we'll this validator to reactive form.

Adding Validator to Reactive Form

Now we'll import Custom Validator(confirm-password.validator.ts) to registration-form.component.ts and will update the form as following:


import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup,Validators } from '@angular/forms';
import { ConfirmPasswordValidator } from './confirm-password.validator';

@Component({
  selector: 'app-registration-form',
  templateUrl: './app-registration-form.component.html',
  styleUrls: ['./app-registration-form.component.scss'],
})

export class RegistrationFormComponent implements OnInit {
  registerForm: FormGroup;
  submitted:boolean=false;

  constructor(private fb: FormBuilder) { }

  ngOnInit() {
    this.registerForm = this.fb.group({
      email: ['']
      password:[''],
      confirmPasswod:['']
    },{
       validator: ConfirmPasswordValidator.MatchPassword
    });
  }
  
  onSubmit() {
    this.submitted=true;
   }
}

Now we'll update template file as following to show the error if password didn't match.

<form [formGroup]="registerForm" novalidate>
  Email:
  <input type="text" formControlName="email">
  Password:
  <input type="password" formControlName="password">
  Confirm Password:
  <input type="password" formControlName="confirmPassword">
  <div class="error" *ngIf="registerForm.get('confirmPassword').errors && registerForm.get('confirmPassword').errors.ConfirmPassword">
   Passsword and ConfirmPassword didn't match.
  </div>
</form>

Thanks for reading the article.


Also, read:


If you like this post, please share it with your friends.
Match Password Validation in Angular Reactive Forms Match Password Validation in Angular Reactive Forms Reviewed by Unknown on September 25, 2018 Rating: 5

1 comment:

  1. Take a look at this project https://github.com/angular-material-extensions/password-strength
    Feedback are appreciated <3

    ReplyDelete

Powered by Blogger.