I'm trying to create a password match validation in a register form, but Angular never enters the custom validation, and I cannot seem to figure out why. The form is as follows.
this.userSettingsForm = this.fb.group({
username: [
'',
[
Validators.required,
Validators.minLength(4)
]
],
password: [''],
password_confirm: ['']
},
{
Validator: this.passwordMatchValidator
});
The validation function is the following;
passwordMatchValidator() {
const password = this.userSettingsForm.get('password').value;
const confirmPassword = this.userSettingsForm.get('password_confirm').value;
if(password.errors && !confirmPassword.errors.passwordMatchValidator) {
return;
}
if(password !== confirmPassword) {
confirmPassword.setErrors({ notSame: true});
}
else {
confirmPassword.setErrors(null);
}
}
Using the following to display errors
<ng-container *ngIf="userSettingsForm.controls.password_confirm.errors">
{{ userSettingsForm.controls.password_confirm.errors.message }}
</ng-container>
But the form always submits as valid. What do I miss?