Help Angular by taking a 1 minute survey!Go to surveyHome

AsyncValidator

An interface implemented by classes that perform asynchronous validation.

      
      interface AsyncValidator extends Validator {
  validate(control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null>

  // inherited from forms/Validator
  validate(control: AbstractControl): ValidationErrors | null
  registerOnValidatorChange(fn: () => void)?: void
}
    

Methods

Method that performs async validation against the provided control.

validate(control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null>
      
      validate(control: AbstractControl): Promise<ValidationErrors | null> | Observable<ValidationErrors | null>
    
Parameters
control AbstractControl

The control to validate against.

Returns

Promise<ValidationErrors | null> | Observable<ValidationErrors | null>: A promise or observable that resolves a map of validation errors if validation fails, otherwise null.

Usage notes

Provide a custom async validator directive

The following example implements the AsyncValidator interface to create an async validator directive with a custom error key.

import { of as observableOf } from 'rxjs'; @Directive({ selector: '[customAsyncValidator]', providers: [{provide: NG_ASYNC_VALIDATORS, useExisting: CustomAsyncValidatorDirective, multi: true}] }) class CustomAsyncValidatorDirective implements AsyncValidator { validate(control: AbstractControl): Observable<ValidationErrors|null> { return observableOf({'custom': true}); } }
      
      
  1. import { of as observableOf } from 'rxjs';
  2.  
  3. @Directive({
  4. selector: '[customAsyncValidator]',
  5. providers: [{provide: NG_ASYNC_VALIDATORS, useExisting: CustomAsyncValidatorDirective, multi:
  6. true}]
  7. })
  8. class CustomAsyncValidatorDirective implements AsyncValidator {
  9. validate(control: AbstractControl): Observable<ValidationErrors|null> {
  10. return observableOf({'custom': true});
  11. }
  12. }