It's not necessary to use nested form groups and a custom ErrorStateMatcher for confirm password validation. These steps were added to facilitate coordination between the password fields, but you can do that without all the overhead.
Here is an example:
this.registrationForm = this.fb.group({
username: ['', Validators.required],
email: ['', [Validators.required, Validators.email]],
password1: ['', [Validators.required, (control) => this.validatePasswords(control, 'password1') ] ],
password2: ['', [Validators.required, (control) => this.validatePasswords(control, 'password2') ] ]
});
Note that we are passing additional context to the validatePasswords method (whether the source is password1 or password2).
validatePasswords(control: AbstractControl, name: string) {
if (this.registrationForm === undefined || this.password1.value === '' || this.password2.value === '') {
return null;
} else if (this.password1.value === this.password2.value) {
if (name === 'password1' && this.password2.hasError('passwordMismatch')) {
this.password1.setErrors(null);
this.password2.updateValueAndValidity();
} else if (name === 'password2' && this.password1.hasError('passwordMismatch')) {
this.password2.setErrors(null);
this.password1.updateValueAndValidity();
}
return null;
} else {
return {'passwordMismatch': { value: 'The provided passwords do not match'}};
}
Note here that when the passwords match, we coordinate with the other password field to have its validation updated. This will clear any stale password mismatch errors.
And for completeness sake, here are the getters that define this.password1
and this.password2
.
get password1(): AbstractControl {
return this.registrationForm.get('password1');
}
get password2(): AbstractControl {
return this.registrationForm.get('password2');
}