Angular 4 Custom Validator ngIf not displaying error <span>

2.4k views Asked by At

I have created 2 custom form validators both of them are working but the message is not displaying when I use an ngIf condition in the template. However for build in validators the messages are displaying. Both of these validators are registered in the component and there are no errors in the console.

Component Template:

<label for="username">Username</label>
<input formControlName='username' type="text" id="username" class="form-control">
<div *ngIf="username.touched && username.invalid">
   <span class="text-danger" *ngIf='username.errors.required'>Username is required</span>
   <span class="text-danger" *ngIf="username.errors.minlength">Username should be min {{ username.errors.minlength.requiredLength }} characters</span>
   <span class="text-danger" *ngIf='username.errors.cannotHaveSpace'>Username can't have space (Custom Validation)</span>
   <span class="text-danger" *ngIf="username.errors.shouldBeUnique">Username is already taken (Custom Validation)</span>
</div>

Validators Code:

static cannotHaveSpace(control: AbstractControl) : ValidationErrors | null{
  if((control.value as string).indexOf(' ')>=0)
  return {cantHaveSpace: true}; 
  return null;
}
static shouldBeUnique(control: AbstractControl): Promise< ValidationErrors | null >{
  return new Promise((resolve,reject)=>{
    setTimeout(()=>{
        if(control.value=='Saad')
            resolve({shouldbeUniqe:true});
       else resolve(null);
    },2000) 
  });
}
1

There are 1 answers

0
AT82 On BEST ANSWER

You have typos...

*ngIf="username.errors.cannotHaveSpace"
*ngIf="username.errors.shouldBeUnique"

should be...

*ngIf="username.errors.cantHaveSpace"
*ngIf="username.errors.shouldbeUniqe"

Not showing your TS code, but also make sure that the async validator is marked as the third argument in it's own array :)