the sign-up button only enables if signupForm is valid , but right now I have one issue , the button is enabling even though the password and confirm password does not match
is my this.equalWithPasswordValidator. implementation wrong ?
Any idea ? Thanks.
#html code
<button mat-raised-button class="full-width v-btn-lrg mt-0px" color="primary" type="submit"
[disabled]="signupForm.invalid">
{{labels.BUTTON.SETUP}}
</button>
#ts code
this.signupForm = this.fb.group({
confirmPassword: [
'',
[Validators.required, this.equalWithPasswordValidator.bind(this)],
],
password: [
'',
[
this.validatePasswordRequired,
this.validateMinimumPassword,
this.validatePasswordUpperCase,
this.validatePasswordLowerCase,
this.validatePasswordSpecialCharacter,
this.validateOneNumber,
],
],
});
}
equalWithPasswordValidator(): ValidatorFn {
return (control: AbstractControl): ValidationErrors | null => {
const equal = control.value === this.signupForm.get('password').value;
return equal ? { notEqual: { value: 'Passwords do not match' } } : null;
};
}
CodePudding user response:
You need to apply a validator to the FormGroup so you can get access to both controls. Here's one approach to creating a validator to compare two fields...
// component
form = new FormGroup({
password: new FormControl('', [ yourValidators... ]),
confirmPassword: new FormControl('', [ yourValidators... ])
}, {
validators: [ equivalentValidator('password', 'confirmPassword') ]
});
// equivalent.validator.ts
import { AbstractControl, ValidationErrors, ValidatorFn } from '@angular/forms';
export const equivalentValidator = (firstControlName: string, secondControlName: string): ValidatorFn => {
return (control: AbstractControl): ValidationErrors | null => {
const firstControl = control.get(firstControlName);
const secondControl = control.get(secondControlName);
if (secondControl.value && secondControl.value !== firstControl.value) {
secondControl.setErrors({ notEqual: true });
}
return null;
};
};
In this example, I'm only setting an error on the second field if it doesn't match the first. Instead of setting the error message here, I'm just setting an error of notEqual
so the validator can be re-used across forms.