Angular Async Validators

Learn Angular Async Validators with AsyncValidatorFn, server-side validation, username availability, email uniqueness, debounce, switchMap, architecture diagrams, enterprise examples, best practices, and interview questions.

Async Validators allow Angular applications to perform validation that depends on external resources, such as databases, REST APIs, or authentication services.

Unlike synchronous validators, asynchronous validators execute after synchronous validation succeeds and return an Observable or Promise.

Async Validators are commonly used for:

  • Username Availability
  • Email Uniqueness
  • Employee ID Validation
  • PAN Validation
  • Account Number Verification
  • Coupon Code Validation
  • Customer Lookup
  • Product Code Validation

They are one of the most frequently asked Angular Reactive Forms interview topics.


Table of Contents

  • What are Async Validators?
  • Why Use Async Validators?
  • Validation Lifecycle
  • AsyncValidatorFn
  • Creating an Async Validator
  • Using Async Validators
  • Async Validation States
  • Debouncing Requests
  • switchMap for HTTP Calls
  • Enterprise Banking Example
  • Best Practices
  • Common Mistakes
  • Top 10 Interview Questions
  • Summary

What are Async Validators?

An Async Validator validates user input using asynchronous operations such as:

  • REST APIs
  • Database queries
  • Authentication services
  • External systems

Unlike synchronous validators, they return:

  • Observable<ValidationErrors | null>
  • Promise<ValidationErrors | null>

Example

Username

↓

API Call

↓

Database

↓

Available?

↓

Valid / Invalid

Async Validation Architecture

flowchart TD

User

User --> FormControl

FormControl --> AsyncValidator

AsyncValidator --> RESTAPI

RESTAPI --> Database

Database --> ValidationResult

ValidationResult --> FormControl

FormControl --> UI

Why Use Async Validators?

Some validations cannot be performed locally.

Examples

  • Username already exists
  • Email already registered
  • Employee ID exists
  • PAN already linked
  • Customer account exists
  • Referral code validity

Without Async Validators

  • Duplicate records
  • Invalid submissions
  • Poor user experience

With Async Validators

  • Live validation
  • Better data integrity
  • Immediate feedback
  • Improved user experience

Validation Lifecycle

Angular executes validators in this order.

User Input

↓

Built-in Validators

↓

Custom Validators

↓

Async Validators

↓

Validation Complete

If synchronous validation fails, Angular does not execute asynchronous validators.


Validation Lifecycle Architecture

flowchart LR

UserInput

UserInput --> SyncValidators

SyncValidators --> Passed

Passed --> AsyncValidator

AsyncValidator --> RESTAPI

RESTAPI --> Result

AsyncValidatorFn

Angular provides the AsyncValidatorFn interface.

export interface AsyncValidatorFn {

(
control: AbstractControl
):

Observable<ValidationErrors | null>

|
Promise<ValidationErrors | null>;

}

Creating an Async Validator

Example

import {
AbstractControl,
AsyncValidatorFn,
ValidationErrors
} from '@angular/forms';

import { map } from 'rxjs/operators';

export function usernameValidator(

userService: UserService

): AsyncValidatorFn {

return (

control: AbstractControl

) =>

userService

.checkUsername(

control.value

)

.pipe(

map(

exists =>

exists

?

{

usernameTaken: true

}

:

null

)

);

}

Async Validator Flow

sequenceDiagram

participant User

participant FormControl

participant Validator

participant API

participant Database

User->>FormControl: Enter Username

FormControl->>Validator: Validate

Validator->>API: HTTP Request

API->>Database: Check Username

Database-->>API: Exists

API-->>Validator: Response

Validator-->>FormControl: Validation Result

Using Async Validators

constructor(
private fb: FormBuilder,
private service: UserService
){}

registrationForm =

this.fb.group({

username:[

'',

{

asyncValidators:[
usernameValidator(
this.service
)
],

updateOn:'blur'

}

]

});

Using updateOn: 'blur' prevents API requests on every keystroke.


Form Status During Validation

Reactive Forms expose a pending state while asynchronous validation is running.

this.registrationForm
.get('username')
?.pending

Possible states

State Meaning
VALID Validation passed
INVALID Validation failed
PENDING Async validation running
DISABLED Control disabled

Validation State Flow

flowchart TD

Input

Input --> Pending

Pending --> API

API --> Valid

API --> Invalid

Showing Validation Messages

<input

formControlName="username">

<div

*ngIf="
registrationForm
.get('username')
?.pending
">

Checking availability...

</div>

<div

*ngIf="
registrationForm
.get('username')
?.errors?.['usernameTaken']
">

Username already exists.

</div>

Using debounceTime()

Avoid sending HTTP requests for every keystroke.

control.valueChanges

.pipe(

debounceTime(500)

);

Benefits

  • Fewer API requests
  • Better performance
  • Improved user experience
  • Reduced server load

Note: debounceTime() is commonly applied when subscribing to valueChanges. It is not typically placed inside the validator itself.


Debounce Flow

flowchart LR

Typing

Typing --> debounceTime

debounceTime --> AsyncValidator

AsyncValidator --> API

Using switchMap()

switchMap() automatically cancels outdated HTTP requests.

control.valueChanges

.pipe(

switchMap(

value =>

this.service

.checkUsername(

value

)

)

);

Example

User types

A

↓

An

↓

Ang

↓

Angular

Only the last request continues.


switchMap Architecture

flowchart TD

Typing

Typing --> Request1

Typing --> Request2

Typing --> Request3

Typing --> Request4

Request1 --> Cancelled

Request2 --> Cancelled

Request3 --> Cancelled

Request4 --> Response

updateOn Strategies

Angular supports three validation strategies.

updateOn:'change'

Runs on every value change.


updateOn:'blur'

Runs when the field loses focus.


updateOn:'submit'

Runs only during form submission.


updateOn Comparison

Strategy Trigger Best For
change Every keystroke Local validation
blur Field loses focus Async API validation
submit Form submit Large forms

Enterprise Banking Example

Customer Registration

Validations

  • Customer ID
  • PAN Number
  • Mobile Number
  • Email
  • Account Number

Architecture

flowchart TD

Customer

Customer --> RegistrationForm

RegistrationForm --> AsyncValidator

AsyncValidator --> BankingAPI

BankingAPI --> CustomerDatabase

CustomerDatabase --> ValidationResult

ValidationResult --> RegistrationForm

Examples

  • Duplicate PAN
  • Existing account
  • Registered email
  • Customer ID verification
  • Mobile number uniqueness

Async Validators vs Sync Validators

Sync Validator Async Validator
Runs immediately Waits for async result
No API call Calls external service
Returns ValidationErrors/null Returns Observable or Promise
Fast Network dependent
Local validation Server validation

Performance Best Practices

Practice Benefit
Use updateOn: 'blur' Reduce unnecessary requests
Use switchMap() Cancel outdated requests
Avoid duplicate HTTP calls Better scalability
Cache repeated lookups when appropriate Better performance
Return meaningful error keys Easier error handling
Handle server errors gracefully Better UX

Common Mistakes

Calling APIs on Every Keystroke

Avoid unnecessary network traffic.

Prefer

updateOn:'blur'

or debounce user input.


Not Handling Pending State

Always inform users when validation is running.

Example

Checking username...

Ignoring HTTP Errors

Handle API failures gracefully.

catchError(()=>

of(null)

)

This prevents the form from remaining in an invalid state because of a transient network error.


Returning Incorrect Types

Always return

Observable<ValidationErrors | null>

or

Promise<ValidationErrors | null>

Performing Business Logic Inside Validators

Validators should only validate.

Move business logic into services.


Best Practices

  • Use async validators only when server validation is required.
  • Prefer updateOn: 'blur' for expensive validations.
  • Use switchMap() to cancel stale requests.
  • Handle HTTP failures gracefully.
  • Display a loading indicator during validation.
  • Return descriptive error keys.
  • Keep validators reusable.
  • Unit test validator functions.

Advantages

Feature Benefit
Live Validation Better UX
Server Verification Accurate validation
Duplicate Detection Better data quality
Observable Support Reactive programming
Reusable Cleaner architecture
Enterprise Ready Large-scale applications

Top 10 Angular Async Validators Interview Questions

1. What are Async Validators?

Answer

Async Validators validate form controls using asynchronous operations such as HTTP requests, database lookups, or external services.


2. What does an Async Validator return?

Answer

An Async Validator returns either:

  • Observable<ValidationErrors | null>
  • Promise<ValidationErrors | null>

3. What is AsyncValidatorFn?

Answer

AsyncValidatorFn is an Angular function type used to implement reusable asynchronous validation logic.


4. When are Async Validators executed?

Answer

Angular executes asynchronous validators only after all synchronous validators pass successfully.


5. Why use updateOn: 'blur'?

Answer

It delays validation until the user leaves the field, reducing unnecessary HTTP requests and improving application performance.


6. What is the pending state?

Answer

pending indicates that asynchronous validation is currently running and a validation result has not yet been received.


7. Why use switchMap()?

Answer

switchMap() cancels outdated HTTP requests and ensures that only the latest validation request is processed.


8. What is the difference between Sync and Async Validators?

Answer

Synchronous validators execute immediately using local logic, while asynchronous validators depend on external resources and return an Observable or Promise.


9. What are common Async Validator use cases?

Answer

  • Username availability
  • Email uniqueness
  • Customer lookup
  • Employee ID validation
  • PAN verification
  • Account number validation

10. What are Async Validator best practices?

Answer

  • Use updateOn: 'blur'.
  • Display loading indicators.
  • Handle server errors.
  • Reuse validator functions.
  • Use switchMap() for request cancellation.
  • Keep validators focused on validation only.

Interview Cheat Sheet

Topic Remember
Interface AsyncValidatorFn
Return Type Observable / Promise
Validation Order After synchronous validators
Pending State pending
Best Trigger updateOn: 'blur'
Cancel Requests switchMap()
Delay Requests debounceTime()
Common Use Username availability
HTTP Errors catchError()
Best Practice Validate only when necessary

Summary

Angular Async Validators extend Reactive Forms by enabling validation against external systems such as databases and REST APIs. They are essential for scenarios like username availability, email uniqueness, and customer verification. By combining AsyncValidatorFn, updateOn: 'blur', switchMap(), proper error handling, and user-friendly loading indicators, developers can build responsive, scalable, and enterprise-ready forms with excellent user experience.


Key Takeaways

  • ✔ Async Validators perform server-side validation.
  • ✔ They return an Observable or Promise.
  • ✔ Angular runs them only after synchronous validation succeeds.
  • ✔ Use updateOn: 'blur' to minimize unnecessary API calls.
  • pending indicates validation is in progress.
  • ✔ Use switchMap() to cancel outdated requests.
  • ✔ Handle server failures gracefully with catchError().
  • ✔ Keep validators reusable and side-effect free.
  • ✔ Display validation progress to users.
  • ✔ Async Validators are a key Angular Reactive Forms interview topic.

Next Article

➡️ 58-FormArray-QA.md