#How to do async form validation on ngSubmit?

8 messages · Page 1 of 1 (latest)

dreamy nymph
#

this is my code:

  ngOnInit() {
    this.form = new FormGroup({
      name: new FormControl('', Validators.required),
      lat: new FormControl('', Validators.required),
      lon: new FormControl('', Validators.required),
      countryId: new FormControl('', Validators.required)
    }, null, this.isDupeCity());

    this.loadData();
  }

<!-- extra code -->
isDupeCity(): AsyncValidatorFn {
    return (control: AbstractControl): Observable<{ [key: string]: any } | null> => {

      var city = <City>{};
      city.id = (this.id) ? this.id : 0;
      city.name = this.form.controls['name'].value;
      city.lat = +this.form.controls['lat'].value;
      city.lon = +this.form.controls['lon'].value;
      city.countryId = +this.form.controls['countryId'].value;

      var url = environment.baseUrl + 'api/Cities/IsDupeCity';
      return this.http.post<boolean>(url, city).pipe(map(result => {

        return (result ? { isDupeCity: true } : null);
      }));
    }
  }

The problem is that the async validator gets called on every keystroke. I'm following a book on Angular & C# and this is the book's github code. The author says "...we can reasonably expect the isDupeCity validator to be called once or twice for each form submission, which is perfectly fine in terms of performance impact. Everything is fine, then. Let's move on"

vapid chasm
#

You should use Sync Validators to make sure that what can be validated locally is valid first. Async Validators won't be called until all the Sync Validators pass.

dreamy nymph
#

That's what the book said too ("Async validators are called after Sync Validators pass")

#

but my problem is the Async is called on every keystroke - is there a way to only call when the *submit button is pressed?

#

@vapid chasm

vapid chasm
#

Don't use Async Validators? At the point the submit button is pressed you are no longer validating you are submitting

dreamy nymph
#

Ok. seems a little strange Async Validators exist... there would be like 50 HTTP calls by the time someone actualy finishes the form

vapid chasm
#
  1. I agree I haven't found a valid use-case
  2. You just need to build your sync validators to be more restrictive so that doesn't happen.