3

I would like to perform validation with tthe server to check if an email is already registered but only on blur not on value change

I have an option to add multiple controls and this is how ive organized my form

    ngOninit(){
      this.userForm = this._formBuilder.group({
       others: this._formBuilder.array([])  //multiple
      });

      this.onAddControl();  //allows adding multiple items
    }



    onAddControl(){

        return this._formBuilder.group({
         email: ['' [this._validateServ.emailDoesntExistsValidator.bind(this._validateServ)]
         ],

       });
   }
 }

Now on the _validateServ

emailDoesntExistsValidator(control) {
  if (control.value != undefined) {
    if(!this.emailValueValidator(control)){
       return this._authService.checkExists("email",control.value)  //http request
        .map(response => {
          if (response) {
            return {'emailTaken': true};
         }
      });
    }

  }
}

I would like the email validation to run on blur since it is performing a http request so that i can show the waiting as http request is being performed The above works but works on each keypress but not on blur event

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Geoff
  • 6,277
  • 23
  • 87
  • 197

1 Answers1

1

I don't know that you can delay control validation.

But there are two things you could delay:

  • The HTTP request. The debounceTime() operator lets you wait for n milliseconds after the user has finished typing to execute the request. See this example.
  • The displaying of the error. Even though the validity of the field is calculated as the user types, you can still wait for blur to show the error. Set a flag to true when the field blurs: <input (blur)="displayError=true">. Then use that flag to display the error: <div *ngIf="error && displayError">Error message</div>.
Community
  • 1
  • 1
AngularChef
  • 13,797
  • 8
  • 53
  • 69