Sub topic 12
Asynchronous checks and their pitfalls
This chapter assumes you already know the built-in constraint attributes, setCustomValidity, ValidityState, and accessible inline errors from earlier chapters. You should also be comfortable with fetch, promises, and async/await.
Why some rules cannot be synchronous
Built-in validation runs in the browser against data it already has. Some rules need information that only the server has:
- Whether a username or email address is already registered.
- Whether a coupon code exists and has not expired.
- Whether a postal code matches a city.
- Whether a domain name resolves.
The Constraint Validation API has no concept of "pending". A control is valid or invalid at the moment you ask. An asynchronous check must therefore be adapted to that model. You start a request, keep the field's validity message up to date, and write the result back with setCustomValidity when the response arrives.
The result is a small state machine for one field, shown below.
A complete working example
The markup adds a status element next to the username field. The aria-live="polite" attribute makes screen readers announce changes to its text without moving focus.
<form id="signup" action="/signup" method="post">
<label for="username">Username</label>
<input id="username" name="username" required minlength="3" maxlength="20"
pattern="[a-z0-9_]+" aria-describedby="username-status" autocomplete="username">
<p id="username-status" aria-live="polite"></p>
<button type="submit">Sign up</button>
</form>The script assumes an endpoint, GET /api/username-available?name=..., that returns JSON such as {"available": true}.
const username = document.getElementById('username');
const status = document.getElementById('username-status');
const DEBOUNCE_MS = 400;
let timer = null;
let controller = null;
async function checkAvailability(name) {
controller?.abort();
controller = new AbortController();
const { signal } = controller;
try {
const url = `/api/username-available?name=${encodeURIComponent(name)}`;
const response = await fetch(url, { signal });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const { available } = await response.json();
if (signal.aborted) return;
const message = available ? '' : 'That username is already taken.';
username.setCustomValidity(message);
status.textContent = available ? 'Username is available.' : message;
} catch (error) {
if (error.name === 'AbortError') return;
username.setCustomValidity('');
status.textContent =
'Could not check availability. We will check again when you submit.';
}
}
username.addEventListener('input', () => {
clearTimeout(timer);
controller?.abort();
// Clear any earlier custom error so only the built-in rules are tested.
username.setCustomValidity('');
if (!username.validity.valid) {
status.textContent = '';
return;
}
// Block submission until the answer arrives.
username.setCustomValidity('Still checking availability.');
status.textContent = 'Checking...';
timer = setTimeout(() => checkAvailability(username.value), DEBOUNCE_MS);
});Each design choice in this script guards against a specific failure. The sections below take them in turn.
Pitfall 1: stale responses (race conditions)
Network responses do not arrive in the order the requests were sent. Suppose the user types alice, then changes it to alice2. If the response for alice arrives last, it overwrites the result for alice2. The field then shows an error or a success for a value it no longer contains.
There are two defenses, and the example uses both.
- Cancel the previous request.
AbortControllerstops the oldfetch. Its promise rejects with an error whosenameisAbortError, which thecatchblock ignores. - Check before writing.
if (signal.aborted) return;makes sure a response that slipped through never touches the field.
A third option works without AbortController. Remember the value you asked about, and discard the response if input.value has changed by the time it arrives.
Pitfall 2: too many requests
Without a delay, every keystroke sends a request. That wastes bandwidth and loads your server, and it can trigger rate limits. Debouncing waits until the user pauses typing before sending anything. The example clears and restarts a 400 ms timer on every input event.
Also skip the request when the built-in rules already fail. A value that is too short cannot be available, so the check would only add load.
Pitfall 3: the form submits while a check is pending
The user can type a name and press Enter before the response returns. If the field is valid during that window, the form submits with an unchecked value.
The example handles this by setting a custom error, Still checking availability., as soon as a check is scheduled. The browser then blocks submission and shows that message. The error is replaced when the response arrives.
Note the order in the input handler. It clears the custom error first and reads validity.valid second. If it read validity while the old custom error was still set, the field would look invalid even when the built-in rules pass.
Pitfall 4: what to do when the check fails
A request can fail because the user is offline, the server returns a 500, or the response is malformed. You must choose what the field does.
| Policy | Behavior on failure | Use when |
|---|---|---|
| Fail open | Clear the error, tell the user the check failed, allow submission | The server re-checks anyway, as with usernames |
| Fail closed | Keep the field invalid until a check succeeds | The value is useless without confirmation |
Fail open is usually right for availability lookups, because the server must reject duplicates regardless. Whichever policy you choose, tell the user in the status text. A silent failure looks the same as success.
A related mistake is leaving the "Still checking" message in place after a failure. Then the user is blocked with a message that is no longer true. The catch block in the example clears it explicitly.
Pitfall 5: the result can be out of date by submit time
A positive answer means "available at the moment of the check". Another user can register the same name a second later. This is a time-of-check to time-of-use gap. No client code can close it.
Only the server can, and only by enforcing the rule atomically. The usual way is a unique constraint in the database. The insert fails if the name exists, and the server returns a field error for username. Your page must be ready to display that error after submit, using the same error element as the live check.
Pitfall 6: information leaks
An availability endpoint tells anyone who calls it whether an account exists. For usernames this is usually acceptable. For email addresses it lets an attacker test which people have accounts on your service, which is called account enumeration.
Mitigations include:
- Rate-limit the endpoint per IP address and per session.
- Do not offer live lookups for sensitive identifiers such as email. Report the problem only after submission, or send a confirmation email in every case.
- Return the same response shape for all inputs, and avoid timing differences you can control.
Pitfall 7: accessibility of delayed messages
Because results arrive after the user has moved on, announcements need care.
- Put the status in a polite live region, as in the example. Do not use
aria-live="assertive"for routine results, because it interrupts the user mid-typing. - Link the status to the input with
aria-describedbyso it is read when the field is focused. - Do not announce "Checking..." on every keystroke if screen reader output becomes noisy. A debounced start of the check is a reasonable moment to announce.
- When the check fails with an error, set
aria-invalid="true"as you would for any other error, and clear it when the value changes. - Never rely on color alone. The status text carries the meaning.
Pitfall 8: custom validity is not cleared automatically
setCustomValidity keeps its message until you set it again. If the user edits the field and your code does not clear the old error, the field stays invalid even for good input. This is the most common asynchronous bug in practice.
In the example, every input event begins by calling setCustomValidity(''). Every code path that ends a check, success or failure, also sets the message explicitly. When you write your own version, trace each path and confirm that the custom message is cleared or replaced.
Testing asynchronous checks
Test the timing cases, not only the happy path.
- Type a taken name and wait. The field should be invalid with the "taken" message.
- Type quickly, changing the value several times. Only the last value's result should appear. In browser developer tools, throttle the network and use request blocking to delay one response and watch for stale results.
- Press Enter while "Checking..." is showing. The form must not submit.
- Go offline and type. The status should say the check failed, and the field should not stay blocked if you chose fail open.
- Edit a taken name into a free one. The error must clear.
- Disable JavaScript and submit a taken name. The server must reject it with a clear message.
Exercise
A user types "bob", and a request starts. They change the value to "bobby" before the first response arrives. The response for "bob" arrives after the response for "bobby", and "bob" is taken. Without any protection, what does the field show, and name two changes to the code that prevent it?
Show answer
The field shows "That username is already taken." for the value "bobby", even though "bobby" was reported available. The stale response overwrote the correct one. Two fixes are to abort the earlier request with AbortController so its response is never processed, and to compare the current input value with the value that was checked before writing the result. Skipping a write when signal.aborted is true achieves the same thing. Debouncing also reduces how often this happens but does not eliminate it.
Exercise
Why does the example set a custom error of "Still checking availability." while a request is pending, and what must the catch block do about it?
Show answer
The message makes the field invalid so the browser blocks submission until the result is known. Without it, the user could submit an unchecked value during the wait. If the request fails, the catch block must clear it with setCustomValidity('') (when failing open), or the user stays blocked by a message that no longer describes the situation.
Exercise
The live check says "alice" is available, but the signup request is rejected on the server with a duplicate error. Give a likely cause and say where the fix belongs.
Show answer
Another user registered "alice" between the check and the submission, a time-of-check to time-of-use gap. The fix belongs on the server: enforce uniqueness with a database unique constraint, catch the violation, and return a field error for username that the page displays in the same error element.