I am currently in the process of designing a registration page that includes fields for confirming passwords and emails. Users are required to re-enter their password and email address. Below is the structure 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 validation function for the password fields is as follows (the same principle applies for the email fields):
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 Outcome:
The validation should update whenever there are changes to either the password
or passwordConfirmed
, and display an error on the passwordConfirmed
field if the values do not match.
Current Issue:
The error persists even after editing the passwordConfirmed
field. The error displays properly when either field is modified.
Solution Attempted
I attempted to modify the conditional statement in the validator to eliminate the error from passwordConfirm
:
if (!match) {
passwordConfirm.setErrors({passwordMatchError: true});
return {passwordMatchError: true};
} else {
passwordConfirm.setErrors({passwordMatchError: null}); <-- this line
return {passwordMatchError: null};
}
However, this action did not remove the error. Instead, it simply set the error value to null. The field remained marked as invalid, and the error persisted, which was confirmed by the console log shown here:
https://i.sstatic.net/C6wpV.png
Are there alternate methods to manually eliminate an error from a form control, or is there another approach to resolving this issue?
(Angular & Angular forms version 7.2.0)