1

I have a custom async validation function. It works well, but before submitting, I check if the Form is valid - it isn't. It's in PENDING status. How should I solve this? Can I wait for the async validation? Or can I skip the async validation there?

I prefer if I could keep the updatevalueandvalidity loop.

//Custom ASyncValidation function
checkUniqueProxy(): AsyncValidatorFn {
return (control: AbstractControl) => {
  if (!control.valueChanges) {
    return of(null);
  } else {
    return control.valueChanges.pipe(
      debounceTime(1000),
      distinctUntilChanged(),
      switchMap(value => this.api.get('My_API_ENDPOINT', {proxy: value})),
      map((data:any) => {
        return data?.unique ? null : {uniqueError: true};
      })
    ).pipe(first())
  }
}



//SAVE FORM 
save(): void {

for (const i in this.Form.controls) {
  if (this.Form.controls.hasOwnProperty(i)) {
    this.Form.controls[i].markAsDirty();
    this.Form.controls[i].updateValueAndValidity();
  }
}
//AT THIS POINT THE FORM IS IN PENDING STATUS
if (!this.Form.valid) return this.notification.createNotification('error', 'Validation error!', 'Please correct the form!')
/// SUBMIT
}
flowstacker
  • 95
  • 2
  • 9
  • thre're a large SO about your question [here](https://stackoverflow.com/questions/36919011/how-to-add-debounce-time-to-an-async-validator-in-angular-2). Really I like the code proposed in this [link](https://tutorialsforangular.com/2021/03/24/async-validators-in-angular/) using `delay` – Eliseo Oct 12 '21 at 18:14
  • My question isn't about debounce; My question is: before submitting, I validate the form with the FOR loop, after that I check if the form is valid, it's not, it's PENDING - It is making a http call, but it doesn't wait for it to finish - so invalid. How should I approach this? – flowstacker Oct 12 '21 at 19:06
  • Is pending because your async validator is wrong created. – Eliseo Oct 12 '21 at 19:08
  • I tried some from the the first link, I couldn't get the second validation link example to work. But still no luck. Form.updateValueAndValidity() does not wait for async validatiors. – flowstacker Oct 13 '21 at 06:40

1 Answers1

0

I solved it like this, If anyone has any better solution, feel free to post it.

//Submit function
save(): void {
  for (const i in this.Form.controls) {
    if (this.Form.controls.hasOwnProperty(i)) {
      this.Form.controls[i].markAsDirty();
      this.Form.controls[i].updateValueAndValidity();
    }
  }
  //At this point ASYNC validation is in pending status
  this.Form.statusChanges.pipe(takeWhile(x => x == 'PENDING', true), filter(x => x != 'PENDING')).subscribe(d => {
      if (!this.Form.valid) return this.notification.createNotification('error', 'Validation error!', 'Please correct your mistakes!')
      
      //And now send data to server or something.
  })

}
TmTron
  • 17,012
  • 10
  • 94
  • 142
flowstacker
  • 95
  • 2
  • 9