1

I have tried to call remote validation by using below code

In component file

Validation code

this.formCompany = this.fb.group({
    varEmail: [null, Validators.compose([Validators.required, Validators.maxLength(150),this.emailExist.bind(this)])],
}});

function for check email exist or not

emailExist(control: FormControl) {

    if(control.value) {  
      this.services.emailExist(control.value).subscribe(res => {this.checkEmailExist = res;
        if(this.checkEmailExist.exist > 0) {
            return { 'emailexist': true };
        } else {
             return null;
        }
        } );
    } else {
        return null;
    }
}

HTML Code

<div fxLayout="row" fxLayoutWrap="wrap">
   <md-input-container class="ml-xs mr-xs" style="width: 60%">
      <input mdInput placeholder="Email Address" maxlength="150"  [ngModel]="CompanyEdit.varEmail" [formControl]="formCompany.controls['varEmail']">
   </md-input-container>
<small *ngIf="formCompany.controls['varEmail'].hasError('required') && formCompany.controls['varEmail'].touched" class="mat-text-warn">Please insert email address.</small>
<small *ngIf="formCompany.controls['varEmail'].hasError('maxlength') && formCompany.controls['varEmail'].touched" class="mat-text-warn">Email address can not exceed 150 characters.</small>
<small *ngIf="formCompany.controls['varEmail'].hasError('emailexist') && formCompany.controls['varEmail'].touched" class="mat-text-warn">Email address already exist.</small>
</div>

This code not working.

CBA
  • 194
  • 13

1 Answers1

1

You need to bind this so that you have have the correct (outside) scope of this. By binding this you can refer to this.services for example (which is outside this emailExist function).

I suggest you read this excellent question + answers about the this-keyword: How does the "this" keyword work?

So what you need to do is simply:

this.emailExist.bind(this)

in your Validators array.

AJT82
  • 60,574
  • 21
  • 115
  • 147
  • It working now and got response from service. But validation doesn't work – CBA Jun 12 '17 at 13:24
  • Okay... what does *doesn't work* mean? And what is your response if it's valid, what is the response if it's not? You are not setting any validator in the subscribe :) – AJT82 Jun 12 '17 at 14:10
  • Looking closer at your code... having the custom validator... it will call the service really many times... maybe want to rethink that? – AJT82 Jun 12 '17 at 14:51
  • Would you maybe rethink about the request and make the request based on some other condition, because this way is perhaps not the best. This makes a bunch of api calls, and if you do it while typing it wouldn't even have time to execute the previous call.... – AJT82 Jun 13 '17 at 06:21
  • Yes right. I have tried to call this service on change but it's not possible to call service on onChange event. – CBA Jun 13 '17 at 06:39