2

Async Validator sends request to JSON each time, when typing in Email form. It checks existing of email, for typing each letter. How can call server and check once, not on every single letter?

isEmailExist(): AsyncValidatorFn  {
   return (control: AbstractControl): Observable<any> => {
     return this.usersService.getUserByEmail(control.value).pipe(
        debounceTime(2000),
        map(users => {
            if (users.some(user => user.email.toLowerCase() === control.value.toLowerCase())) {
               return { isExist: true };
            } else {
               return null;
            }
        })
     ) 
   }
  }
1

2 Answers 2

2

The debounceTime operator must be piped after an Observable that emits keyup events. You could use the fromEvent operator to achieve that.

1

Merei, you can use {updateOn:'blur'}, see the docs

Another option is not use a validator and check isEmailExist in submit

And another option is that you "check" the email in a debounceTime but of the value changes. Imagine you has a variable "check" and a control

  check=false;
  control=new FormControl('',Validators.required,this.customValidator().bind(this))

the bind(this)make that you can use a variable of your component, so your customValidator can be like

  customValidator(){
    return (control)=>{
    if (!this.check)  //if the variable in component is false return of(null)
      return of(null)
                      //else you call to the service
     return this.usersService.getUserByEmail(control.value).pipe(
       map(users => {
          if (users.some(user => user.email.toLowerCase() ===
                                   control.value.toLowerCase())) {
              return { isExist: true };
          } else {
             return null;
          }
     })
    }
  }

Now, after define the FormControl you subscribe to valueChanges

this.control.valueChanges.pipe(debounceTime(300)).subscribe(_=>{
  this.check=true;
  this.control.updateValueAndValidity({emitEvent:false});
  this.check=false;
})

In this stackblitz I simulate the call to your service with a fool function

Not the answer you're looking for? Browse other questions tagged or ask your own question.