angularangular-reactive-formsformbuilder

angular forms 'confirm password' showing error


I am using angular forms to create a register form. I have made a custom validator which checked if the password is the same as confirm password field. Although the error of 'password do not match' does not show, the input is still red until all the fields are entered.

The form builder with the custom validator method checkPasswords

this.registerForm = this.formBuilder.group({
  firstName: ['', Validators.required],
  lastName: ['', Validators.required],
  email: ['', [Validators.required, Validators.email]],
  password: ['', [Validators.required]],
  confirmPassword: ['', [Validators.required]]
  },
  { validator: this.checkPasswords });


checkPasswords(group: FormGroup) {
  // here we have the 'passwords' group
  let pass = group.get('password').value;
  let confirmPassword = group.get('confirmPassword').value;
  return pass === confirmPassword ? null : { notSame: true };
}

and the html below

<mat-form-field required>
    <input matInput type="password" placeholder="Password" formControlName="password">
    <mat-error>Password is not valid</mat-error>
</mat-form-field>

<mat-form-field required>
    <input matInput type="password" placeholder="Confirm password"
           formControlName="confirmPassword"
           [errorStateMatcher]="matcher">
    <mat-error *ngIf="registerForm.hasError('notSame')">Passwords do not match</mat-error>
</mat-form-field>

I have tried to do some debugging, and I think it is because the form group status is 'invalid' until all fields are entered, but the form group control for confirmPassword is showing valid. How can I get status for confirmPassword to use the status of its control?

Thanks


Solution

  • This is because of angular material. If there is no error on the given control, <mat-error> will not be visible. You need to set the error on the confirmPassword field to display the error.