i have implmented one custom validator in angular reactive forms but it is not displaying the error message. please find code in the below link. https://stackblitz.com/edit/angular-yalkcb?file=src%2Fapp%2Fapp.component.ts
2 Answers
I ve fixed it for you. see https://stackblitz.com/edit/angular-ewfmt4?file=src%2Fapp%2Fapp.component.ts for working state.
I've changed validateFname
-> validateFname()
because it is not the validatorFn, but rather a validatorFnFactory
regForm.controls['fname'].errors.forbiddenName
-> regForm.controls['fname'].errors?.forbiddenName
in the tamplate. this ?.
operator doesn't evaluate the errors.forbiddenName if errors is null. It makes your console cleaner
const forbidden = false;
-> let forbidden = false;
because this is not a constant according to logic

- 10,117
- 13
- 21
I have fixed and simplified it for you:
On your component.html, add the safe navigation '?' such that the expression will only be evaluated if an error exists (in other words, if errors
is not null)
<tr>
<td>
<span *ngIf="regForm.controls['fname'].errors?.forbiddenName">
invalid name
</span>
</td>
</tr>
and on your component.ts,
export function validateFname(control: AbstractControl) {
let val = control.value;
if (val.includes('s')) {
// return {'forbiddenName': {'value': val}};
return {'forbiddenName': true};
}
return null;
}

- 40,384
- 10
- 95
- 107
-
please take a look of this question https://stackoverflow.com/q/70779997/811293 – joseluisbz Jan 20 '22 at 02:06