Santhosh
Santhosh

Reputation: 1079

unable to print custom validator errors in angular reactive forms

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

Upvotes: 0

Views: 296

Answers (2)

wentjun
wentjun

Reputation: 42516

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;

}

Upvotes: 1

Andrei
Andrei

Reputation: 12001

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

Upvotes: 1

Related Questions