Reputation: 11
I have a custom validation in the FormGroup level as defined below:
this.createForm = this.builder.group({
pass: this.builder.control('',
[
Validators.required,
Validators.minLength(5)
]),
conPass: this.builder.control('',
[
Validators.required,
Validators.minLength(5)
]),
}, { validator: [isTheSame('pass', 'conPass')] });
static isTheSame(c1: string, c2: string): ValidatorFn {
return (form: FormGroup): ValidationErrors | null => {
const c1Input = form.controls[c1]?.value;
const c2Input = form.controls[c2]?.value;
return (c1Input !== c2Input) ? { notTheSame: true } : null;
};
}
I want to check if the notTheSame
is true or not. I used *ngIf="createForm .errors?.notTheSame"
and display a text if it returns true
. But it doesn't work even notTheSame
has a value of true
.
Upvotes: 0
Views: 1410
Reputation: 804
You need to set errors on the control level, here I'm attaching code you can use to achieve your desired results.
you can create one function in one service file
service.ts
static MatchPassword(control: AbstractControl) {
const password = control.get('pass').value;
const confirmPassword = control.get('conPass').value;
if (password !== confirmPassword) {
control.get('conPass').setErrors({ passwordNotMatched: true });
}
else {
return false;
}
}
And you can use it in your form during initialization
component.ts
this.createForm = this.builder.group({
pass: this.builder.control('',
[
Validators.required,
Validators.minLength(5)
]),
conPass: this.builder.control('',
[
Validators.required,
Validators.minLength(5)
]),
}, { validator: UtilityService.MatchPassword });
And in your HTML
<p *ngIf="formName['conPass'].errors && formName['conPass'].errors.passwordNotMatched">Password not matched </p>
Upvotes: 2
Reputation: 1079
Try this I hope it worked for you. Html
<span class="text-danger *ngIf="createForm.get('conPass')?.hasError('notEquivalent') && createForm.get('conPass')?.touched">Password and Confirm password not matched.</span>
Upvotes: 0
Reputation: 860
Have you tried this:
createForm.hasError(‘notTheSame’)
Btw, createForm.errors is an array.
Upvotes: 0