Angular › Forms
How would you create a custom asynchronous validator that checks something against a server, such as whether a username is already taken?
AdvancedAnswer
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.