Search code examples
angularvalidationangular-reactive-formsangular-validation

How to identify which custom validation function is causing error in Reactive Forms


I have number of validators assigned to a formControl with formControlName as firstName. How to know which validation is giving error so that I can give appropriate message

Following is my custom made validation function for required

export function required() {
  return function(control:FormControl)
  {
    var value: string = control.value;
    value = value.trim();
    if(value.length == 0)
      return {required:true};    
    return null;
  } 
 }

and using is like this

<md-error [hidden]="!firstName.errors.required || (!firstName.touched && !submitted)">
   Name is required
</md-error>

I get the following error

ERROR TypeError: Cannot read property 'required' of null

Solution

  • <md-error *ngIf="firstName.hasError('required') && (firstName.touched || submitted)">
       Please enter the required field
    </md-error>
    

    this worked for me.

    firstName.errors.required doesnt work

    thank you for all the help.

    if there are multiple validation fails and multiple messages then u can show only the first error message by adding in css

    md-error:not(:first-of-type) { display: none; }