Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 control validation when a user finishes typing

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

like image 807
Geoff Avatar asked Jul 12 '26 09:07

Geoff


1 Answers

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>.
like image 193
AngularChef Avatar answered Jul 13 '26 21:07

AngularChef



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!