Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two controls value validation

About

I am trying to compare the value of password and confirm password and if found mismatch then message to be shown.

Due to some reasons it shows nothing. Am I missing anything in below code?

Form Group Validation work

    this.resetPasswordForm = new FormGroup({
        password: new FormControl("", [
            Validators.required,
            Validators.minLength(8), 
            Validators.maxLength(40)
        ]),
        password_confirmation: new FormControl("", [
            Validators.required
        ]),
    });

Html

    <input type="password" formControlName="password_confirmation" />
            
    <span *ngIf="resetPasswordForm.controls.password_confirmation.errors
        && resetPasswordForm.controls.password_confirmation.dirty 
        && resetPasswordForm.controls.password_confirmation.touched">
        
        <ng-container *ngIf="resetPasswordForm.controls.password_confirmation.errors.required;else second">
            Confirm password is required
        </ng-container>
        <ng-template #second>
            <ng-container *ngIf="resetPasswordForm.controls.password_confirmation.value 
                == resetPasswordForm.controls.password.value">
                Password and confirm password mismatch
            </ng-container>
        </ng-template>
    </span>
like image 993
Pankaj Avatar asked Dec 07 '25 10:12

Pankaj


1 Answers

Your password_confirmation validation only has Validation.required. So when this field has any value, resetPasswordForm.controls.password_confirmation.errors will be false and any error message will not be shown.

You have to create a validation function that checks the password and password_confirmation values are identical. This will resetPasswordForm.controls.password_confirmation.errors makes true when two fields have different values.


const validatePasswordMatch = (control: AbstractControl): {[key: string]: any} | null => {
  const password = this.resetPasswordForm?.get('password')?.value as string;
  const passwordConfirm = control.value as string;

  if (password !== passwordConfirm) {
    return {passwordMatch: true};
  }

  return null;
};


this.resetPasswordForm = new FormGroup({
    password: new FormControl("", [
        Validators.required,
        Validators.minLength(8), 
        Validators.maxLength(40)
    ]),
    password_confirmation: new FormControl("", [
        Validators.required,
        validatePasswordMatch
    ]),
});

Then you can show password confirmation error like this.

    <ng-template #second>
        <ng-container *ngIf="resetPasswordForm.controls.password_confirmation.errors.passwordMatch">
            Password and confirm password mismatch
        </ng-container>
    </ng-template>
like image 94
N.F. Avatar answered Dec 09 '25 00:12

N.F.