简体   繁体   中英

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

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> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM