Home > Enterprise >  How to validate password and confirm password using angular 12 material?
How to validate password and confirm password using angular 12 material?

Time:06-04

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>

CodePudding user response:

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;
        }
    }
}

CodePudding user response:

Custom Validation: Password Confirmation

Mustafa is right that you're better off using reactive forms when you are using Angular Material and the mat-error tags. However, here is a more complete version including all the validation messages, since you asked for 'A LOT OF' help.

I improved the Mustafa's validator a little too. This will help you get rid of all weirdness with the validation messages.

The visibility icon logic was removed since material password inputs already have this functionality built in.

Script:

form: FormGroup;

constructor(private fb: FormBuilder) {}

ngOnInit() {
  this.form = this.fb.group(
    {
      password: [
        '',
        [
          Validators.required,
          Validators.minLength(8),
          Validators.maxLength(100),
        ],
      ],
      confirmPassword: [
        '',
        [
          Validators.required,
          Validators.minLength(8),
          Validators.maxLength(100),
        ],
      ],
    },
    { validator: CustomValidators.MatchingPasswords }
  );
}

The improved custom validator:

export class CustomValidators {

    static MatchingPasswords(control: AbstractControl) {
        const password = control.get('password').value;
        const confirmPassword = control.get('confirmPassword').value;
        const currentErrors = control.get('confirmPassword').errors
        const confirmControl = control.get('confirmPassword')

        if (compare(password, confirmPassword)) {
            confirmControl.setErrors({...currentErrors, not_matching: true});
        } else {
            confirmControl.setErrors(currentErrors)
        }
    }
}

function compare(password: string,confirmPassword: string) {
    return password !== confirmPassword && confirmPassword !== ''
}

Template:

<form [formGroup]="form">
  <mat-form-field>
    <mat-label>Password</mat-label>
    <input
      matInput
      type="password"
      placeholder="Password"
      formControlName="password"
    />
    <mat-error *ngIf="form.get('password').hasError('required')">
      Password is required!
    </mat-error>
    <mat-error *ngIf="form.get('password').hasError('minlength')">
      Password should be longer than 8 characters!
    </mat-error>
    <mat-error *ngIf="form.get('password').hasError('maxlength')">
      Password can't be longer than 100 characters!
    </mat-error>
  </mat-form-field>

  <mat-form-field>
    <mat-label>Confirm Password</mat-label>
    <input
      matInput
      placeholder="Confirm your password..."
      formControlName="confirmPassword"
      type="password"
    />
    <mat-error *ngIf="form.get('confirmPassword').hasError('required')">
      Password confirmation is required!
    </mat-error>
    <mat-error *ngIf="form.get('confirmPassword').hasError('minlength')">
      Password should be longer than 8 characters!
    </mat-error>
    <mat-error *ngIf="form.get('confirmPassword').hasError('maxlength')">
      Password can't be longer than 100 characters!
    </mat-error>
    <mat-error *ngIf="form.get('confirmPassword').hasError('not_matching')">
      The password doesn't match!
    </mat-error>
  </mat-form-field>
</form>

Here's an example on Stackblitz for you to play with.

  • Related