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
confirmPasswordinitially shows as valid, it's because initially, bothpasswordandconfirmPasswordare empty strings… - Will AlexanderpasswordandconfirmPasswordwere both valid and no error text was being displayed, the input box was still red (error color). This was because the formGroup was invalid. I was not referencing the formControl ofconfirmPassword. It is now fix by passing through thepasswordandconfirmPasswordas parameters in the validator - DevStacker