Angular › Forms

How would you create a custom asynchronous validator that checks something against a server, such as whether a username is already taken?

Advanced

Answer

An asynchronous validator function returns an observable or a promise instead of a plain value, letting you perform something like an API call to check availability, with Angular automatically marking the control as pending while waiting and updating its validity once the response arrives.
function uniqueUsernameValidator(userService: UserService): AsyncValidatorFn {
  return (control: AbstractControl) => {
    return userService.checkUsernameAvailable(control.value).pipe(
      map((isAvailable) => (isAvailable ? null : { usernameTaken: true }))
    );
  };
}
Real-world example A signup form checks in real time whether a chosen username is already taken by calling the server through an asynchronous validator, showing a pending indicator while waiting and an error message if the username turns out to be unavailable.

Common follow-ups: How do you avoid sending a request on every single keystroke while the user is still typing the username?;What does the pending status on a form control actually represent?