I'm trying to create a registration page with a password-confirm and email-confirm field where the user has to repeat their password and email. This is the setup of the FormGroup
:
ngOnInit() {
this.basicInfo = this.formBuilder.group({
userName: ['', [Validators.required, Validators.minLength(5)]],
firstName: ['', Validators.required],
lastName: ['',Validators.required],
emails: this.formBuilder.group({
email: ['', [Validators.required, Validators.email]],
emailConfirm: ['', [Validators.required, Validators.email]],
}, {validators: SignUpComponent.checkEmailMatch}),
passwords: this.formBuilder.group({
password: ['', [Validators.required]],
passwordConfirm: ['', Validators.required]
}, {validators: SignUpComponent.checkPasswordMatch})
});
The validator for the password fields is the following (the same for email):
static checkPasswordMatch(group: FormGroup) {
let password = group.get('password');
let passwordConfirm = group.get('passwordConfirm');
if (password == null || passwordConfirm == null) return null; // prevent errors
let match = password.value === passwordConfirm.value;
if (!match) {
passwordConfirm.setErrors({passwordMatchError: true});
return {passwordMatchError: true};
} else {
return {passwordMatchError: null};
}
}
Expected results
The validator should update whenever password
or passwordConfirmed
are edited, and add the appropriate error to the passwordConfirmed
control if their values are not identical.
What actually happens
The error is only removed when passwordConfirmed
is edited (adding the error works when either is edited)
Attempted solution
I tried modifying the if statement in the validator to remove the error from passwordConfirm
:
if (!match) {
passwordConfirm.setErrors({passwordMatchError: true});
return {passwordMatchError: true};
} else {
passwordConfirm.setErrors({passwordMatchError: null}); <-- this line
return {passwordMatchError: null};
}
This does not remove the error, but instead just sets it to null. The control is still marked as invalid and the error is still there as indicated by this log to the console:
Are there any other ways of manually removing an error from a form control or is there another way to solve this?
(Angular & Angular forms version 7.2.0)