Sub topic 13
Validate asynchronously
Some rules cannot be checked in the browser alone. Whether a username is taken, whether a coupon code is still valid, or whether an address exists all need a server. This chapter covers how Signal Forms runs those checks. It assumes you know form(), schema functions, validate(), and field state signals from earlier chapters. It also assumes you know Angular's resource() and HttpClient at a basic level.
The Signal Forms API is experimental in Angular 21. The option names shown here (params, factory, request, onSuccess, onError) match that release and may change.
How async validation fits in
A synchronous validator such as required() or validate() returns its result immediately. An asynchronous validator starts a request and has no answer until the request finishes. Signal Forms handles this with a third state, called pending, in addition to valid and invalid.
The field exposes this as a signal, pending(), next to valid(), invalid(), and errors(). You can use it to show a spinner and to block submission while a check is running.
The schema function offers two async validators:
| Function | Use it when | You provide |
|---|---|---|
| `validateHttp()` | The check is a single HTTP request | A `request` function and result handlers |
| `validateAsync()` | You need a custom `resource()`, or any non-HTTP async source | `params`, a `factory` that builds a resource, and result handlers |
validateHttp() is the shorter form of validateAsync() for the common case. Both turn a field value into a request, wait for the response, and map the response to either an error object or no error.
Async validators wait for synchronous ones
Async validation does not start until every synchronous validator on the field passes. If the email field is empty or malformed, Signal Forms reports the required or email error and does not call the server.
This ordering matters for two reasons. It saves requests on values that are already known to be bad. It also means the user sees the cheap, instant errors first, and the server error only appears for input that is well formed.
When the user keeps typing, the value changes again before the response arrives. The old result is discarded and a new check starts. You never see a stale answer applied to a newer value, because the request is derived from the current value signal.
A username check with validateHttp()
The next example checks a username against an endpoint. It uses debounce() so the form waits for a pause in typing before it updates the field. That cuts the number of requests.
import { Component, signal } from '@angular/core';
import { provideHttpClient } from '@angular/common/http';
import {
form,
Field,
required,
minLength,
debounce,
validateHttp,
} from '@angular/forms/signals';
@Component({
selector: 'app-signup',
imports: [Field],
template: `
<form (submit)="onSubmit($event)">
<label>Username <input [field]="signupForm.username" /></label>
@if (signupForm.username().pending()) {
<p class="hint">Checking availability...</p>
}
@if (signupForm.username().touched() && signupForm.username().invalid()) {
@for (error of signupForm.username().errors(); track error.kind) {
<p class="error">{{ error.message }}</p>
}
}
<button type="submit" [disabled]="!signupForm().valid()">Sign up</button>
</form>
`,
})
export class SignupComponent {
private readonly model = signal({ username: '' });
protected readonly signupForm = form(this.model, (path) => {
required(path.username, { message: 'Username is required' });
minLength(path.username, 3, { message: 'Use at least 3 characters' });
debounce(path.username, 300);
validateHttp(path.username, {
request: ({ value }) => `/api/usernames/check?name=${encodeURIComponent(value())}`,
onSuccess: (response: { taken: boolean }) =>
response.taken
? { kind: 'taken', message: 'That username is already taken' }
: undefined,
onError: () => ({
kind: 'network',
message: 'Could not check the username. Try again.',
}),
});
});
protected onSubmit(event: Event) {
event.preventDefault();
console.log(this.model());
}
}
export const signupProviders = [provideHttpClient()];Add signupProviders (or just provideHttpClient()) to your application config, because validateHttp() uses Angular's HTTP client.
Walk through the three parts of the validator:
requestreceives the field context. It readsvalue()and returns a URL string. Because it reads a signal, the request is recomputed whenever the value changes.onSuccessreceives the parsed response. Return an error object withkindandmessageto mark the field invalid, orundefinedfor valid.onErrorruns when the request itself fails, for example on a network error or a 500 response. Return an error object, orundefinedif you want to let the user continue.
Use encodeURIComponent() when you put user input in a URL. Without it, a value containing & or # changes the meaning of the query string.
Choosing what happens when the request fails
onError is a policy decision, not a detail. There are two reasonable choices:
- Fail closed. Return an error. The form stays invalid until a check succeeds. Use this when the server rule is a security or integrity requirement.
- Fail open. Return
undefinedand let the user proceed. Use this when the check is a convenience and the server will validate again on submit.
The example above fails closed. Whichever you pick, the server must still enforce the rule when the form is submitted. A client-side check can be skipped, and two users can both pass an availability check for the same name and then collide.
Using validateAsync() with a resource
validateAsync() gives you more control. You map the field value to parameters, and a factory builds an Angular resource() from them.
import { resource, signal } from '@angular/core';
import { form, required, validateAsync } from '@angular/forms/signals';
const model = signal({ coupon: '' });
const orderForm = form(model, (path) => {
required(path.coupon, { message: 'Enter a coupon code' });
validateAsync(path.coupon, {
params: ({ value }) => value(),
factory: (params) =>
resource({
params,
loader: async ({ params: code, abortSignal }) => {
const response = await fetch(`/api/coupons/${encodeURIComponent(code)}`, {
signal: abortSignal,
});
if (!response.ok) {
throw new Error('Lookup failed');
}
return (await response.json()) as { valid: boolean };
},
}),
onSuccess: (result) =>
result.valid ? undefined : { kind: 'coupon', message: 'This coupon is not valid' },
onError: () => ({ kind: 'network', message: 'Could not check the coupon' }),
});
});The abortSignal passed to the loader is cancelled when the parameters change. Passing it to fetch() cancels the stale request on the network, instead of only ignoring its result. Use validateAsync() when you need this kind of control, when the source is not HTTP (for example IndexedDB or a WebSocket call), or when several fields share one resource shape.
Pending state and submission
A field with a running check is neither confirmed valid nor invalid. That has consequences for your template:
- Do not show a "valid" tick just because
invalid()is false. Checkpending()too. - Disable the submit button with
!form().valid()rather thanform().invalid(). A pending field is not yet valid, sovalid()stays false until the check finishes. submit()from the previous chapter runs its action only when the form is valid. With async validators in the schema, make sure the user cannot trigger it while a check is in flight, or the action may run before the server's answer.
Common errors
- No request is sent. A synchronous validator on the same field is failing. Check
errors()for arequiredorminLengtherror first. - A request on every keystroke. You did not add
debounce(). Add it before the async validator in the schema. - The error appears but never clears. The
onSuccesshandler returns an error object in both branches, or returnsnullwhere you wantedundefined. Check the branch that should mean "valid". - Everything fails with an HTTP error.
validateHttp()needsprovideHttpClient()in your application providers. - A spinner that never stops. The request never completes, for example because of a missing timeout on a custom source. Make sure the loader resolves or rejects.
Summary
Async validators run only after the synchronous ones pass. They put the field in a pending state that you read with pending(). validateHttp() covers single HTTP requests, and validateAsync() covers custom resources with cancellation. Decide deliberately whether a failed request should block the user, and always enforce the rule again on the server.
Exercise
A signup form has a username field with required(), minLength(path.username, 3), and a validateHttp() availability check. The user types "ab" and sees "Use at least 3 characters". Does the form send a request to the server? Later the user types "alice" and the server answers { "taken": true }. What does pending() return before the response arrives, what does errors() contain after it arrives, and which onSuccess return value produced that?
Show answer
No request is sent for "ab", because async validators run only after all synchronous validators pass, and minLength fails. For "alice", pending() returns true while the request is in flight. After the response, errors() contains { kind: 'taken', message: 'That username is already taken' }, produced by onSuccess returning an error object when response.taken is true. If it had returned undefined, the field would be valid.
Exercise
Why is [disabled]="!form().valid()" a safer condition for the submit button than [disabled]="form().invalid()" when the form has an async validator?
Show answer
While an async check is running, the field is pending, so invalid() is false and the button would be enabled before the server has answered. valid() is also false during pending, so !form().valid() keeps the button disabled until every check, including the async one, has completed successfully.