angularangular-reactive-formsangular-formsangular2-form-validation

async validator (AsyncValidatorFn) is never subscribed to


I wrote a custom Form Validator but in errors it just has "_isScalar": false, "source": { "_isScalar": false, "source": { "_isScalar": false, "source": {"_isScalar": false}, "operator": {}}, "operator": {"total": 1} and the form is never valid.

This is my Validator:

export function asyncEmailValidator(): AsyncValidatorFn {
  return (control: AbstractControl): Observable<ValidationErrors | null> => {
    return of(control.value).pipe(
      map(res => {
        return res && res.indexOf('example.de') < -1 ? { eMailUnavailable: true } : null;
      }),
      take(1), finalize(() => {})
    );
  };
}

This is how i use it:

emailFormControl = new FormControl('', [
  Validators.required,
  Validators.email,
  asyncEmailValidator()
]);

From debugging i found that the map Block where i check for example.de is never reached and i fail to understand why. The function itself is used and output before the inner return is shown.

I saw this structure in multiple examples online but it just doesn't seem to work for me.

I am using @angular/forms 10.0.14


Solution

  • Asynchronous validators should be specified as a third argument as follows:

     new FormControl('', [Validators.required, Validators.email], [asyncEmailValidator()]);