Issue
I am new to Angular and I have created this custom validator that will check if two controllers' values mismatch. So far the validator works, if the value is mismatched it will attach an error to the controller. But what I really want is to attach the error to the form itself since this is a FormGroup validator. How to do that?
this.createAccountForm = this.builder.group({
pass: this.builder.control('',
[
Validators.required,
Validators.minLength(5)
]),
confirmPass: this.builder.control('',
[
Validators.required,
Validators.minLength(5)
]),
}, { validator: CustomValidators.isControllersMatched('pass', 'confirmPass') });
static isControllersMatched(c1: string, c2: string) {
return (group: FormGroup) => {
let c1Input = group.controls[c1],
c2Input = group.controls[c2];
if (c1Input.value !== c2Input.value) {
return c2Input.setErrors({ notEquivalent: true });
}
else {
return c2Input.setErrors(null);
}
}
}
Solution
I would rather use such a validator
export const isControllersMatched: ValidatorFn = (control:
AbstractControl): ValidationErrors | null => {
const pass = control.get('pass');
const confirmPass = control.get('confirmPass');
return pass && confirmPass && pass.value === confirmPass.value ? null
: { passesDonotMatch: true };
};
FormBuilder looks like this
this.createAccountForm = this.builder.group({
pass: this.builder.control('',
[
Validators.required,
Validators.minLength(5)
]),
confirmPass: this.builder.control('',
[
Validators.required,
Validators.minLength(5)
]),
}, { validator: isControllersMatched });
And finally HTML
<div *ngIf="(createAccountForm.get('confirmPass')?.touched ||
createAccountForm.get('confirmPass')?.dirty) &&
createAccountForm.hasError('passesDonotMatch')"
class="cross-validation-error-message alert alert-danger">
Passwords do not match
</div>
Answered By - Nataly Chkhan
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.