Async custom validators using Angular's resource-based validateAsync() API
Angular's validateAsync uses the resource API for async validation. Validators must provide params, factory, onSuccess, and optional onError callbacks.
Structure:
params: Function that computes params from field context
factory: Function that creates ResourceRef from params signal
onSuccess: Maps resource result to validation errors
onError: Optional handler for resource errors
Use Cases:
Database lookups via services with resource API
Complex async business logic with Angular resources
Note: For HTTP validation, prefer httpValidators which provides a simpler API specifically designed for HTTP requests.
Use derivation functions for complex mappings or logic that can't be easily expressed as a JavaScript expression.
Example usage
derivations: { // Country to currency mapping getCurrencyForCountry: (context) => { const countryToCurrency: Record<string, string> = { 'USA': 'USD', 'Germany': 'EUR', 'France': 'EUR', 'UK': 'GBP', 'Japan': 'JPY' }; return countryToCurrency[context.formValue.country as string] ?? 'USD'; }, // Complex tax calculation calculateTax: (context) => { const subtotal = context.formValue.subtotal as number ?? 0; const state = context.formValue.state as string; const taxRates: Record<string, number> = { 'CA': 0.0725, 'NY': 0.08, 'TX': 0.0625 }; return subtotal * (taxRates[state] ?? 0); }, // Format phone number formatPhoneNumber: (context) => { const phone = context.fieldValue as string ?? ''; const digits = phone.replace(/D/g, ''); if (digits.length === 10) { return `(${digits.slice(0,3)}) ${digits.slice(3,6)}-${digits.slice(6)}`; } return phone; }}
Field configuration using a derivation function:
// Derivation is defined on the target field (currency), not the source field (country){ key: 'currency', type: 'select', logic: [ { type: 'derivation', functionName: 'getCurrencyForCountry', dependsOn: ['country'] } ]}
Automatic request cancellation when field value changes
Built-in integration with Angular's resource management
Simpler than asyncValidators for HTTP use cases
Important:onSuccess uses inverted logic - it maps SUCCESSFUL HTTP responses to validation errors. For example, if the API returns { available: false }, your onSuccess should return { kind: 'usernameTaken' }.