Sub topic 12
Asynchronous checks and their pitfalls
This chapter assumes you know setCustomValidity, checkValidity, and fetch with async/await. It builds on the custom validity chapter.
Why some checks are asynchronous
Built-in constraints run instantly in the browser. Some rules need the server. "Is this username taken?" is the standard example, because only the server knows. The Constraint Validation API has no async hook, so you wrap the lookup yourself. Start the request, then use setCustomValidity when the answer arrives.
A working pattern
The markup needs a status element that screen readers announce:
<label for="username">Username</label>
<input id="username" name="username" required minlength="3" maxlength="20"
pattern="[a-z0-9_]+" aria-describedby="username-status">
<p id="username-status" role="status"></p>The script uses a debounce timer and a ticket counter:
const username = document.getElementById('username');
const status = document.getElementById('username-status');
let timer;
let latest = 0;
username.addEventListener('input', () => {
clearTimeout(timer);
username.setCustomValidity('');
status.textContent = '';
if (!username.checkValidity()) return; // let built-in rules report first
username.setCustomValidity('Checking availability...');
const ticket = ++latest;
timer = setTimeout(() => check(ticket, username.value), 400);
});
async function check(ticket, value) {
try {
const url = `/api/username-available?name=${encodeURIComponent(value)}`;
const res = await fetch(url);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const { available } = await res.json();
if (ticket !== latest) return; // a newer check replaced this one
const message = available ? '' : 'That username is taken.';
username.setCustomValidity(message);
status.textContent = message || 'Username is available.';
} catch {
if (ticket !== latest) return;
username.setCustomValidity(''); // do not block the user on a network error
status.textContent = 'Could not check availability. The server will check on submit.';
}
}Pitfalls
Stale responses
Responses can arrive out of order. If the user types anna and then annabel, the reply for anna may land last and overwrite the correct result. The ticket comparison discards any reply that is not for the latest input. AbortController solves the same problem by cancelling the older request.
Too many requests
Without a delay, every keystroke sends a request. The 400 ms debounce waits for a pause in typing. Skipping the lookup when built-in rules already fail also saves requests.
Submitting while a check is pending
The "Checking availability..." message is deliberate. It makes the field invalid, so the browser blocks submission until the check finishes. If you left the field valid during the lookup, a fast user could submit before the answer arrived.
Failures and a stuck field
A failed request must clear the pending error. Otherwise the user cannot submit at all. The example treats a network error as "unknown" and leaves the final decision to the server.
The answer can change
Availability is true when you check and may be false a second later. Another user can claim the name between the lookup and the submit. The client result is a hint. The server must repeat the check when it handles the form and enforce it, ideally with a unique database constraint.
Information leaks and abuse
A public availability endpoint lets anyone test whether a username or email exists. Rate-limit it. For sensitive data such as email addresses, consider skipping live checks and reporting the problem only after submission.
Summary of rules
| Problem | Remedy |
|---|---|
| Out-of-order replies | Ticket counter or `AbortController` |
| Request on every keystroke | Debounce, skip when built-in rules fail |
| Submit during pending check | Set a custom error until the reply arrives |
| Network failure blocks the user | Clear the error in `catch` |
| Race with other users | Server re-check plus a unique constraint |
Exercise
A user types "sam", then quickly corrects it to "samir". The request for "samir" finishes first and returns "available". The older request for "sam" then returns "taken". Which line in the example prevents the field from showing "taken", and what does it do?
Show answer
The line if (ticket !== latest) return; does. Each input increments latest and gives the request its own ticket. When the "sam" reply arrives, its ticket is older than latest, so the function returns without calling setCustomValidity or updating the status text. The result for "samir" stays.
Exercise
Why must the server check username availability again on submit, even though the client already confirmed it was available?
Show answer
The client check can be bypassed, and the answer can go stale. Another user may register the same name after the lookup. The server needs its own check, backed by a unique constraint, to decide the outcome reliably.