Search code examples
angularangular-validation

Custom Async validation form in pending status


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
}

Solution

  • 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.
      })
    
    }