Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate password and confirm password using angular 12 material?

I would like a lot of help from you. I'm not able to validate the password field and confirm password using angular material in version 12. I'm using this structure below in html.

<div>
  <mat-form-field>
    <mat-label>Password</mat-label>
    <input matInput 
           type="password" 
           placeholder="Digite sua senha" 
           [type]="hide ? 'password' : 'text'"
           [formControl]="passwordFormControl" />
    <mat-icon matSuffix (click)="hide = !hide">
           {{ hide ? 'visibility' : 'visibility_off' }}
    </mat-icon>
    <mat-error>               
    </mat-error>
  </mat-form-field>
</div>
<div>
  <mat-form-field>
    <mat-label>Confirm Password</mat-label>
    <input matInput
           type="password" 
           placeholder="Digite novamente sua senha"
           [type]="hide ? 'password' : 'text'" 
           [formControl]="passwordFormControl"/>
    <mat-icon matSuffix (click)="hide = !hide">
      {{ hide ? 'visibility' : 'visibility_off' }}
    </mat-icon>
    <mat-error>               
    </mat-error>
  </mat-form-field>
</div>
like image 898
Leogomes Avatar asked Nov 16 '25 23:11

Leogomes


1 Answers

You can use the reactive form to validate. this is how you form structure will look like here you can take care of other styling and all

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

constructor(
    private fb: FormBuilder,
    ....rest
) { }
this.form=this.fb.group({
           .... other enteries
           password: ['', Validators.compose([
                Validators.required,
                Validators.minLength(8),
                Validators.maxLength(100)
            ])
            ],
            confirmPassword: ['', Validators.compose([
                Validators.required,
                Validators.minLength(8),
                Validators.maxLength(100)
            ])
 },{ validator: ConfirmPasswordValidator.MatchPassword})

This is how your validator will look

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

export class ConfirmPasswordValidator {
    /**
     * Check matching password with confirm password
     * @param control AbstractControl
     */
    static MatchPassword(control: AbstractControl) {
        const password = control.get('password').value;

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

        if (password !== confirmPassword) {
            control.get('confirmPassword').setErrors({ConfirmPassword: true});
        } else {
            return null;
        }
    }
}
like image 153
Mustafa Kunwa Avatar answered Nov 18 '25 19:11

Mustafa Kunwa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!