Angular 4 Form Password Match Validator

Angular 4 Form Password and Conform Password Match Validator

How to Validate Password and Confirm Password in Angular 4?

How to Validate Form in Angular 4?
This custom validator is used for Password and Conform Password in Angular 4 which allows us to have fields that must be equal to some other field’s i.e.
1.     Password field
2.     Conform Password field

This custom validator is very useful for password confirmation validation, validate card etc.

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

export class AppComponent implements OnInit {
    userForm: FormGroup;
    password = 'password';

    constructor(private fBuilder: FormBuilder) {
        this.userForm = fBuilder.group({
            name: fBuilder.control(null, Validators.required),
            age: fBuilder.control(null, [Validators.required, Validators.minLength(2), Validators.maxLength(2)]),
            email: fBuilder.control(null, [Validators.required, Validators.email]),
            password: fBuilder.control(null, Validators.required),
            repeatPassword: fBuilder.control(null, [Validators.required, matchValidator(this.password)])
        });
        console.log(this.userForm);
    }

    onSubmit(): void {
        console.log(this.userForm.value);
    }
}

import {FormGroup, Validators, FormControl} from '@angular/forms';

export function matchValidator(fieldName: string) {
    let fcfirst: FormControl;
    let fcSecond: FormControl;

    return function matchValidator(control: FormControl) {

        if (!control.parent) {
            return null;
        }

        // INITIALIZING THE VALIDATOR.
        if (!fcfirst) {
            //INITIALIZING FormControl first
            fcfirst = control;
            fcSecond = control.parent.get(fieldName) as FormControl;

            //FormControl Second
            if (!fcSecond) {
                throw new Error('matchValidator(): Second control is not found in the parent group!');
            }

            fcSecond.valueChanges.subscribe(() => {
                fcfirst.updateValueAndValidity();
            });
        }

        if (!fcSecond) {
            return null;
        }

        if (fcSecond.value !== fcfirst.value) {
            return {
                matchOther: true
            };
        }

        return null;
    }
}

Example 2 –
import { Directive, forwardRef, Attribute } from '@angular/core';
import { NG_VALIDATORS, Validator, Validators, AbstractControl, ValidatorFn } from '@angular/forms';

@Directive({
    selector: '[Equalvalidate][formControlName],[formControl],[ngModel]',
    providers: [
        {
            provide: NG_VALIDATORS,
            useExisting: forwardRef(() => EqualValidator),
            multi: true
        }
    ]
})

export class EqualValidator implements Validator {

    constructor(@Attribute('Equalvalidate') public Equalvalidate: string) { }

    validate(abControl: AbstractControl): { [key: string]: any } {
        // Get self value.
        let val = abControl.value;

        // Get control value.
        let cValue = abControl.root.get(this.Equalvalidate);

        // value not equal
        if (cValue && val !== cValue.value) return {
            Equalvalidate: false
        }

        return null;
    }
}

HTML –
<div class="form-group">
    <label for="Password">Password</label>
    <input type="password" class="form-control" id="password" required [(ngModel)]="model.password" name="password" #password="ngModel">
    <div [hidden]="password.valid || password.pristine" class="alert alert-danger">
         Password is required
    </div>
</div>
<div class="form-group">
    <label for="ConfirmPassword">Confirm Password</label>
    <input type="password" class="form-control" id="confirmPassword" required Equalvalidate="password" [(ngModel)]="model.confirmPassword" name="confirmPassword"  #confirmPassword="ngModel">
    <div [hidden]="confirmPassword.valid || confirmPassword.pristine" class="alert alert-danger">
        Password mismatch
    </div>
</div>

Example 3 –
let passwordMatchValidator = function(fg: FormGroup) {
    return fg.get('password').value === fg.get('confirmPassword').value ? null : { 'mismatch': true };
}

const form = new FormGroup({
    password: new FormControl('', Validators.minLength(6), Validators.maxLength(30)),
    passwordConfirm: new FormControl('', Validators.minLength(6), Validators.maxLength(30)),
}, passwordMatchValidator);

Result –

References –

I hope you are enjoying with this post! Please share with you friends. Thank you!!
ANIL SINGH

Hey! I'm Anil Singh. I author this blog. I'm Active Blogger, Programmer. I love learning new technologies, programming, blogging and participating the forum discussions more...
My Blogs - http://www.code-sample.com and http://www.code-sample.xyz
My Books - Google Amazon and Flipkart Book Store!

You Might Also Like
Post a Comment
www.code-sample.com/. Powered by Blogger.