Hey there, I'm currently working with validators in my Angular form setup. Here's a snippet of how it looks - I utilize Validators.compose to combine custom validators. The errors from these validators are then displayed on the HTML component. My goal here is that when the matchingValidator throws an error, I want Angular to skip executing the other two validators.
this.formGroup = this.fb.group(
{
password: ['', [Validators.required, Validators.minLength(8)]],
confirmPassword: ['', [Validators.required, Validators.minLength(8)]]
},
{
validator: Validators.compose([
matchingValidator('password', 'confirmPassword'),
passwordStrengthValidator('password', 'confirmPassword'),
blacklistedPasswordValidator(
'password',
'confirmPassword',
this.blacklistedPasswords
)
])
}
);
Here's the code for the validators:
export function matchingValidator(
passwordControlName = 'password',
passwordConfirmControlName = 'passwordConfirm'
): ValidatorFn {
return (formGroup: FormGroup): ValidationErrors => {
const passwordValue: string = formGroup.get(passwordControlName).value;
const passwordConfirmValue: string = formGroup.get(
passwordConfirmControlName
).value;
if (passwordValue.length && passwordConfirmValue.length) {
return passwordValue !== passwordConfirmValue
? { passwordConfirmation: true }
: null;
}
return null;
};
}
// Similar functions for passwordStrengthValidator and blacklistedPasswordValidator
// HTML code segment below:
<alert type="danger" dismissable="false" *ngIf="formGroup.hasError('passwordConfirmation')">
{{ 'VALIDATION.ERRORS.MATCHING_PASSWORDS' | translate }}
</alert>
<alert type="danger" dismissable="false" *ngIf="formGroup.hasError('invalidPasswordStrength')">
{{ 'VALIDATION.ERRORS.PASSWORD_STRENGTH_INVALID' | translate }}
</alert>
<alert type="danger" dismissable="false" *ngIf="formGroup.hasError('blacklistedPassword')">
{{ 'VALIDATION.ERRORS.PASSWORD_NOT_PERMITTED' | translate }}
</alert>
In essence, I'd like to halt displaying validation errors from other two validators if formGroup.hasError('passwordConfirmation') returns true. How can I go about achieving this? Any guidance would be greatly appreciated as I am relatively new to AngularJS and TypeScript.