'Validation Error in FormGroup level not working
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
.
Solution 1:[1]
Have you tried this:
createForm.hasError(‘notTheSame’)
Btw, createForm.errors is an array.
Solution 2:[2]
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>
Solution 3:[3]
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>
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Hamidreza Vakilian |
Solution 2 | Bansi29 |
Solution 3 |