UI Component Implementation: Forms and States Questions
Implementing forms and the non-happy-path states of UI components in the browser. Covers form building (controlled and uncontrolled inputs, reusable form hooks tracking values, touched fields and errors, dynamic groups of repeating fields, multi-step flows, submit handling), client-side and server-side validation (inline errors, validation timing, cross-field rules, async validation such as username checks with stale-response handling, error summaries, mapping API error responses onto fields), and the states a component must handle: loading and pending, error and retry, empty results, disabled, error boundaries around a failing widget, and edge cases such as double submit, slow or failed networks, drafts preserved across failures, and unexpected input like pasted text or locale differences. Includes building custom inputs and widgets robustly: restricted numeric inputs, comboboxes and custom selects, and date fields with calendar popups, with labels, error association, focus management, announcing errors to assistive technology and keyboard operation. Excludes design-system library governance and tokens, optimistic-update and rollback logic in the client data layer, accessibility strategy as a design practice, and the state-management architecture of the whole application.
A long form is used by people on slow or flaky connections. What do you implement so users do not lose what they typed, double-submit, or get stuck when a submit times out or fails, and how does the UI let them recover?
Sample Answer
Direct answer
Three separate mechanisms, because they fail separately. (1) Save a draft of the answers in browser storage as the user types, and restore it on load, so a reload, a crashed tab or a dropped connection costs nothing. (2) Guard submission twice: a synchronous in-flight check on the client so a double click sends one request, and an idempotency key (a unique value the client generates per submission and sends on every retry of it) so the server can recognise a retry and not repeat the work. (3) Give every submit a deadline and treat the outcome as one of three things: success, refused by the server (a 4xx status), or unknown (timeout, dropped connection, 5xx). Unknown is the case that gets users stuck: keep their answers on screen, say plainly that you could not confirm receipt, and offer a Try again button that is safe to press because of the idempotency key.
Not losing what was typed
- The draft is written to
localStorage(shared across tabs, survives closing the browser) after a short pause in typing, not on every keystroke (that is debouncing: wait until the user stops for a moment, then write once): one write per pause.sessionStoragewould drop the draft when the tab closes, which defeats the purpose here. - Storage can be full (browsers cap it with a size limit called a quota) or blocked (private modes, policies) and then
setItemthrows, so every access is intry/catchand the form works without a draft. - Never put secrets in the draft (passwords, card numbers, one-time codes). Keep to fields that would otherwise be retyped.
- Remove the draft on success, and tell users when one was restored so it is not a surprise. An untouched or fully cleared form is not a draft: the code removes the stored draft instead of saving an empty one, because otherwise the debounced write on first render stores three empty strings and the next visit wrongly says "We restored the answers you had saved".
beforeunloadis registered only while there is unsaved input. The listener callspreventDefault()(MDN: the recommended way to raise the browser's leave-page confirmation) and the browser shows its own generic text, not yours. MDN also says the event can fail to fire on mobile and recommendsvisibilitychange(the event fired when the tab is hidden or shown again) for dependable state saving; the debounced draft write is the real protection, and the prompt is a courtesy.
Never double-submitting
- Client: a
useRefflag set synchronously at the top of the handler. A state flag such aspendingis not visible to a second event that fires before the next render. The button also reports the busy state witharia-disabledand text ("Sending..."), staying focusable. - Server contract: "safe" means a method only reads and changes nothing on the server (GET); "idempotent" means sending the same request several times leaves the server in the same state as sending it once (PUT and DELETE are; creating a record with POST is not). POST is neither safe nor idempotent (MDN): repeating it may repeat its effect, such as creating the same order twice. So the client must not blindly auto-retry a POST that timed out, because the first request may have succeeded. With an idempotency key the retry is safe: the client sends the same value in an
Idempotency-Keyheader for every retry of one submission intent; the server stores the result of the first request under that key and replays it. Stripe documents this design: it saves the status code and body of the first request for a key and returns them for subsequent requests with the same key, compares the parameters and errors if they differ, and may prune keys once they are at least 24 hours old (one vendor's retention window, given as an example; yours is a design choice). - Key lifetime in the code: created at the first submit, reused by every retry, cleared on success and on a 4xx refusal (the server evaluated it and refused it, so the next attempt is a new intent). Three 4xx codes are not refusals of that kind and keep the key: 408 (request timeout: the outcome is unknown, like a client timeout), 409 (a conflict that can mean the same key is still being processed; Stripe documents that a request which conflicts with another one executing concurrently is not saved and may be retried), and 429 (rejected before processing, so a retry with the same key is safe).
Timeouts, failures and recovery
The central scenario, step by step (times are illustrative, with a 10 second client deadline):
- At 0 s the user clicks Submit. The client creates key K and sends the POST with
Idempotency-Key: K. - At 9 s the server saves the application and stores the result under K, but the response is still crawling back over the slow link.
- At 10 s the client deadline fires and aborts the request. The client cannot know whether the server finished, so it shows "We could not confirm that your application was received", keeps every answer, and relabels the button "Try again". The key stays.
- At 14 s the user clicks Try again. The client sends the POST with the same K.
- The server finds K, replays the stored 201 response and creates nothing new. The client shows the confirmation and clears the draft and the key. One application exists, which is what the timeout test below asserts.
| Outcome | What the client knows | UI | Key |
|---|---|---|---|
| 2xx | Done | Confirmation, draft cleared | Cleared |
| 4xx except 408, 409 and 429 (for example 422) | Server refused it | "The server did not accept your answers", fields keep their values | Cleared |
| 5xx, 408, 409, 429, timeout, offline, connection reset | Unknown: the server may have done the work | "We could not confirm that your application was received", Try again button | Kept |
The deadline is an AbortController aborted by setTimeout, with clearTimeout in finally; controller.abort() rejects the fetch and ends the request. AbortSignal.timeout(ms) is a shorter spelling (it rejects with a TimeoutError; MDN lists it as available since 2024), but MDN notes you cannot cancel its timer, so the explicit timer keeps cleanup deterministic. Choose the deadline from your own server latency data; a reasonable starting point is a little above the 99th percentile of normal response time (the time that 99% of requests beat), and a long deadline on a flaky link keeps the user waiting with no information.
navigator.onLine is only a hint (MDN: true means a network is attached, not that the internet is reachable), so use it to show an "You seem to be offline" note at most; decide success or failure from the request. Automatic retries with backoff (retrying after waits that grow, for example 1 s, 2 s, 4 s, so a struggling server is not hammered) are reasonable here only because the key makes the POST idempotent; without a key, retry manually, on the user's click.
Code
import { useEffect, useRef, useState } from 'react';
const DRAFT_KEY = 'application-draft';
const empty = { fullName: '', email: '', coverNote: '' };
function readDraft(storage) {
try { return JSON.parse(storage.getItem(DRAFT_KEY)); } catch { return null; }
}
function writeDraft(storage, values) {
try {
// An untouched or fully cleared form is not a draft: store nothing, so the next visit is not told "we restored your answers".
if (JSON.stringify(values) === JSON.stringify(empty)) storage.removeItem(DRAFT_KEY);
else storage.setItem(DRAFT_KEY, JSON.stringify(values));
} catch { /* quota or blocked storage: the form still works */ }
}
export function ApplicationForm({ fetchImpl = fetch, storage = window.localStorage, timeoutMs = 10000, debounceMs = 300 }) {
const [values, setValues] = useState(() => readDraft(storage) ?? empty);
const [restored] = useState(() => readDraft(storage) !== null);
const [status, setStatus] = useState('idle'); // idle | pending | unconfirmed | rejected | done
const inFlight = useRef(false);
const idempotencyKey = useRef(null); // one key per submission intent, reused by every retry of it
// Debounced draft: at most one storage write per pause in typing, never after success.
useEffect(() => {
if (status === 'done') return;
const t = setTimeout(() => writeDraft(storage, values), debounceMs);
return () => clearTimeout(t);
}, [values, status, storage, debounceMs]);
// Ask the browser to confirm leaving only while there is something to lose.
useEffect(() => {
const dirty = status !== 'done' && JSON.stringify(values) !== JSON.stringify(empty);
if (!dirty) return;
const handler = (e) => { e.preventDefault(); e.returnValue = true; };
window.addEventListener('beforeunload', handler);
return () => window.removeEventListener('beforeunload', handler);
}, [values, status]);
async function onSubmit(e) {
e.preventDefault();
if (inFlight.current) return; // double click, or Enter pressed twice
inFlight.current = true;
idempotencyKey.current ??= crypto.randomUUID();
setStatus('pending');
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
try {
const res = await fetchImpl('/api/applications', {
method: 'POST',
signal: controller.signal,
headers: { 'Content-Type': 'application/json', 'Idempotency-Key': idempotencyKey.current },
body: JSON.stringify(values),
});
if (res.ok) {
storage.removeItem(DRAFT_KEY);
idempotencyKey.current = null;
setStatus('done');
} else if (res.status >= 400 && res.status < 500 && ![408, 409, 429].includes(res.status)) {
idempotencyKey.current = null; // the server evaluated it and refused it: the next attempt is a new intent
setStatus('rejected');
} else {
setStatus('unconfirmed'); // 5xx, 408, 409, 429: the server may or may not have done the work; keep the key
}
} catch {
setStatus('unconfirmed'); // timeout, offline, connection reset: outcome unknown
} finally {
clearTimeout(timer);
inFlight.current = false;
}
}
const set = (k) => (e) => setValues({ ...values, [k]: e.target.value });
if (status === 'done') return <p role="status">Application received. Thank you.</p>;
return (
<form onSubmit={onSubmit}>
{restored && <p>We restored the answers you had saved on this device.</p>}
<label htmlFor="fullName">Full name</label>
<input id="fullName" value={values.fullName} onChange={set('fullName')} />
<label htmlFor="email">Email</label>
<input id="email" type="email" value={values.email} onChange={set('email')} />
<label htmlFor="coverNote">Cover note</label>
<textarea id="coverNote" value={values.coverNote} onChange={set('coverNote')} />
<button type="submit" aria-disabled={status === 'pending' ? 'true' : undefined}>
{status === 'pending' ? 'Sending...' : status === 'unconfirmed' ? 'Try again' : 'Submit application'}
</button>
<div role="status">{status === 'pending' ? 'Sending your application' : ''}</div>
<div role="alert">
{status === 'unconfirmed' && 'We could not confirm that your application was received. Your answers are still here and saved on this device. Trying again will not create a second application.'}
{status === 'rejected' && 'The server did not accept your answers. Check them and submit again.'}
</div>
</form>
);
}
The tests render the component with React 18 and Testing Library under jsdom, with a fake server that does the work before the client's deadline expires, which is how a real timeout hides a successful request.
import { describe, it, expect, afterEach, beforeEach } from 'vitest';
import { render, screen, cleanup, waitFor, act, fireEvent } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { ApplicationForm } from './ApplicationForm.jsx';
afterEach(cleanup);
beforeEach(() => window.localStorage.clear());
// A fake server that, like a real one, does the work BEFORE the client's connection times out.
function makeServer(script) {
const records = new Map(); // idempotency key -> stored application
const keysSeen = [];
let calls = 0;
const fetchImpl = (url, { signal, headers, body }) => {
const call = ++calls;
const key = headers['Idempotency-Key'];
keysSeen.push(key);
const action = script[call - 1] ?? 'ok';
if (action === 'ok' || action === 'hang') { if (!records.has(key)) records.set(key, JSON.parse(body)); }
if (action === 'hang') {
return new Promise((_, reject) => signal.addEventListener('abort', () => reject(new DOMException('Aborted', 'AbortError'))));
}
if (/^\d{3}$/.test(action)) return Promise.resolve({ ok: false, status: Number(action) }); // e.g. '503', '422', '409'
return Promise.resolve({ ok: true, status: 201 });
};
return { fetchImpl, records, keysSeen, calls: () => calls };
}
const fill = async (user) => {
await user.type(screen.getByLabelText('Full name'), 'Ada Lovelace');
await user.type(screen.getByLabelText('Email'), 'ada@example.com');
await user.type(screen.getByLabelText('Cover note'), 'I would like to apply.');
};
const submit = (user) => user.click(screen.getByRole('button'));
describe('slow or flaky network', () => {
it('keeps what was typed across a reload, restores it, and clears it on success', async () => {
const user = userEvent.setup();
const server = makeServer([]);
const first = render(<ApplicationForm fetchImpl={server.fetchImpl} debounceMs={20} />);
await fill(user);
await waitFor(() => expect(JSON.parse(localStorage.getItem('application-draft')).coverNote).toBe('I would like to apply.'));
first.unmount(); // simulates the tab being closed or reloaded
render(<ApplicationForm fetchImpl={server.fetchImpl} debounceMs={20} />);
expect(screen.getByLabelText('Full name').value).toBe('Ada Lovelace');
expect(screen.getByText(/restored the answers/)).toBeTruthy();
await submit(user);
await screen.findByText('Application received. Thank you.');
expect(localStorage.getItem('application-draft')).toBeNull();
});
it('an idle visit stores nothing, so the next visit is not told answers were restored', async () => {
const server = makeServer([]);
const first = render(<ApplicationForm fetchImpl={server.fetchImpl} debounceMs={20} />);
await new Promise((r) => setTimeout(r, 100));
expect(localStorage.getItem('application-draft')).toBeNull();
first.unmount();
render(<ApplicationForm fetchImpl={server.fetchImpl} debounceMs={20} />);
expect(screen.queryByText(/restored the answers/)).toBeNull();
});
it('after a timeout keeps the values, says the outcome is unknown, and a retry creates exactly one record', async () => {
const user = userEvent.setup();
const server = makeServer(['hang', 'ok']);
render(<ApplicationForm fetchImpl={server.fetchImpl} timeoutMs={40} debounceMs={20} />);
await fill(user);
await submit(user);
await waitFor(() => expect(screen.getByRole('alert').textContent).toMatch(/could not confirm/));
expect(screen.getByLabelText('Email').value).toBe('ada@example.com');
expect(screen.getByRole('button').textContent).toBe('Try again');
await submit(user);
await screen.findByText('Application received. Thank you.');
expect(server.calls()).toBe(2);
expect(server.keysSeen[0]).toBe(server.keysSeen[1]);
expect(server.records.size).toBe(1);
});
it('sends one request for a double click while pending', async () => {
const user = userEvent.setup();
const server = makeServer(['hang']);
render(<ApplicationForm fetchImpl={server.fetchImpl} timeoutMs={60} debounceMs={20} />);
await fill(user);
await user.dblClick(screen.getByRole('button'));
expect(server.calls()).toBe(1);
await waitFor(() => expect(screen.getByRole('alert').textContent).toMatch(/could not confirm/));
});
it('two submit events in the same tick send one request, which a state flag would not catch', async () => {
const user = userEvent.setup();
const server = makeServer(['hang']);
render(<ApplicationForm fetchImpl={server.fetchImpl} timeoutMs={60} debounceMs={20} />);
await fill(user);
const form = screen.getByRole('button').closest('form');
act(() => { fireEvent.submit(form); fireEvent.submit(form); }); // both run before React re-renders
expect(server.calls()).toBe(1);
await waitFor(() => expect(screen.getByRole('alert').textContent).toMatch(/could not confirm/));
});
it('keeps the key after a 409 or 429, because the outcome may be unknown', async () => {
const user = userEvent.setup();
const server = makeServer(['409', '429', 'ok']);
render(<ApplicationForm fetchImpl={server.fetchImpl} debounceMs={20} />);
await fill(user);
await submit(user);
await waitFor(() => expect(screen.getByRole('alert').textContent).toMatch(/could not confirm/));
await submit(user);
await waitFor(() => expect(server.calls()).toBe(2));
await submit(user);
await screen.findByText('Application received. Thank you.');
expect(new Set(server.keysSeen).size).toBe(1);
});
it('treats 503 as unknown (same key on retry) and 422 as a refusal (new key on the next attempt)', async () => {
const user = userEvent.setup();
const server = makeServer(['503', '422', 'ok']);
render(<ApplicationForm fetchImpl={server.fetchImpl} debounceMs={20} />);
await fill(user);
await submit(user);
await waitFor(() => expect(screen.getByRole('alert').textContent).toMatch(/could not confirm/));
await submit(user);
await waitFor(() => expect(screen.getByRole('alert').textContent).toMatch(/did not accept/));
await submit(user);
await screen.findByText('Application received. Thank you.');
const [k1, k2, k3] = server.keysSeen;
expect([k1 === k2, k2 === k3]).toEqual([true, false]);
});
});
Run with npx vitest run flaky, it prints 7 passing tests (Tests 7 passed (7)). Deliberate breakages make tests fail: generating a new key on every attempt fails the "exactly one record" and the 503/422 key tests, deleting the inFlight check fails the double-click test, replacing it with a check of the pending state passes that test but fails the same-tick test, storing the empty form fails the idle-visit test, and treating every 4xx as a refusal fails the 409/429 test.
Trade-offs
- Idempotency key versus no retry: the key needs server work (a table of key, parameters and stored response), but it is the only way to make "Try again" safe after an unknown outcome. If the backend cannot be changed, make the confirmation screen the recovery path: on a timeout, ask the server whether the record exists before offering another submit.
- Replaying a stored failure: Stripe saves the result of the first execution whatever its status, 500 errors included, so a Stripe-style server answers a retry of a stored 500 with the same 500. The table's "Kept" for 5xx assumes a server built for this client: it stores only results worth replaying (a created record, a deterministic refusal) and re-executes after a transient 5xx, while a gateway 502 or 503 that never reached the application stores nothing, so the retry runs normally.
- Edits after an unknown outcome: the key follows the intent, not the contents, so a retry with changed answers is compared by the server and refused as a mismatch (the Stripe behaviour above) rather than silently creating a second record; the UI then shows the refusal and starts a fresh key.
- Pitfalls: clearing the form on an error; showing a generic "Something went wrong" with no retry; disabling the button forever after a timeout; auto-retrying a plain POST; announcing progress only visually (the
role="status"androle="alert"regions exist from first render so changes are announced).
Running the code
Tested in a node:22 container.
npm i react@18.3.1 react-dom@18.3.1 jsdom vitest@2.1.8 @testing-library/react@16 @testing-library/dom @testing-library/user-event
npx vitest run flaky
vitest.config.js, next to the files: export default { esbuild: { jsx: 'automatic' }, test: { environment: 'jsdom' } }. It lets the JSX compile without a React import and provides document. Without it all the tests fail: those that call userEvent.setup() stop with a TypeError about the missing document, and the rest with ReferenceError: React is not defined.
You have a controlled text field component that must check its value against a server (for example whether a username is taken) and show a pending indicator while the check runs. The user types quickly and responses sometimes return out of order or after the value has changed. How do you implement it so the displayed result always matches the current value, without flooding the server?
Sample Answer
Direct answer
Tie each server check to the exact value that started it, and make every value change cancel the previous check. In a useEffect keyed on the value, start a short timer (a debounce: wait until the user pauses typing) and, when it fires, send one request with an AbortController signal (the browser's built-in way to cancel a request). The effect's cleanup clears the timer and calls abort(), so a newer value both prevents unsent checks and cancels sent ones. After the await, drop the answer if its signal was aborted. That makes the displayed result always belong to the current value, and a burst of typing costs one request.
A timeline of the effect
Two React terms carry the mechanism. The dependency array (the list [value, valid, delay, check, ignoreStale] at the end of useEffect) tells React to re-run the effect only when one of those values changed. The effect's cleanup is the function the effect returns; React calls it just before the next run of the effect for a changed value, and when the component unmounts. With a 300 ms delay and illustrative typing gaps of 100 ms:
| Time | Event | What the effect and its cleanup do |
|---|---|---|
| 0 ms | value becomes abc (first valid value) | Effect runs: status checking, timer set to fire at 300 ms |
| 100 ms | value becomes abcd | Cleanup of the first run: timer cleared, abort() called on a request that was never sent. New run: timer set to fire at 400 ms |
| 200 ms | value becomes abcde | Cleanup clears the 400 ms timer. New run: timer set to fire at 500 ms |
| 500 ms | typing has paused | Timer fires: one request for abcde is sent |
| 700 ms | user types f, request still in flight | Cleanup calls abort() on the abcde request. New run: timer set for 1000 ms, request for abcdef follows |
Four values were typed (abc, abcd, abcde, abcdef) but only abcde ever reached the network before 700 ms, and that request was cancelled when f arrived; abcdef is sent at 1000 ms if typing pauses. If the abcde reply had already been on its way back, the signal.aborted check after the await makes the component drop it.
The state set
| State | Meaning | Shown to sighted users | Announced to screen readers |
|---|---|---|---|
idle | Value cannot be valid yet (fewer than 3 characters, forbidden characters) | Nothing | Nothing |
checking | Timer pending or request in flight | "Checking..." indicator | Nothing (announcing it on every pause is noise) |
available | Server said the name is free | "maria is available." | The same text, politely |
taken | Server said it is taken | Same message, field marked invalid | The same text, politely |
unknown | The check itself failed | Neutral message, field not marked invalid | The same text, politely |
Instant rules run first: a value that fails the local pattern sends nothing, so most keystrokes of a half-typed name cost no request.
Announcing the result to assistive technology
The message element is a <p role="status"> that is always in the DOM and starts empty; only its text changes. A live region (an area whose changes the screen reader speaks without moving focus) must exist before its content changes, which is why MDN's aria-live examples start from an empty element. role="status" is the polite variant (speech waits for the user to pause), which suits "available" and "taken". The input points to the same element with aria-describedby, so a user who tabs back to the field hears the message again, and aria-invalid="true" is set only for taken, because MDN's guidance is that aria-invalid marks a value that failed validation. The checking state deliberately has no text in the region.
Fail open or fail closed when the check itself errors
If the request fails (network down, HTTP 500), the component enters unknown: a neutral message, no invalid mark, the user can continue. This is fail-open, and it is right when the server enforces uniqueness again on submit (it must, because two people can claim the same name between check and submit, so this check is a convenience, never the authority). Fail-closed (block the form until the check works) is right only when a wrong "valid" would cause irreversible harm and no later check exists; it also makes a flaky endpoint a sign-up outage. Two details: fetch resolves normally on HTTP 404 and 500, so the check function must test res.ok and throw; and an AbortError caused by the user typing again is not a failure and must not produce the "unknown" message.
The component
import { useEffect, useId, useState } from 'react';
export type Availability = 'idle' | 'checking' | 'available' | 'taken' | 'unknown';
const MESSAGES: Record<Availability, (name: string) => string> = {
idle: () => '',
checking: () => '', // the visual indicator shows progress; the live region stays quiet until there is a result
available: (n) => `${n} is available.`,
taken: (n) => `${n} is already taken. Try another username.`,
unknown: () => 'We could not check availability right now. You can continue; we will check again when you submit.',
};
export function UsernameField({
check, // resolves true when the name is taken; must honour the signal
delay = 300,
ignoreStale = true,
}: {
check: (name: string, signal: AbortSignal) => Promise<boolean>;
delay?: number;
ignoreStale?: boolean; // false only exists to prove the tests can fail
}) {
const id = useId();
const [value, setValue] = useState('');
const [status, setStatus] = useState<Availability>('idle');
const valid = /^[a-z0-9_]{3,20}$/.test(value); // instant rule first: no request for names that cannot be valid
useEffect(() => {
if (!valid) {
setStatus('idle');
return;
}
setStatus('checking');
const controller = new AbortController();
const timer = setTimeout(async () => {
try {
const taken = await check(value, controller.signal);
if (ignoreStale && controller.signal.aborted) return; // the value changed while this request was in flight
setStatus(taken ? 'taken' : 'available');
} catch {
if (ignoreStale && controller.signal.aborted) return; // an abort is not a failure
setStatus('unknown'); // fail open: the server re-checks on submit
}
}, delay);
return () => {
clearTimeout(timer); // typing again cancels the pending request before it is even sent
controller.abort(); // and cancels one that is already in flight
};
}, [value, valid, delay, check, ignoreStale]);
return (
<div>
<label htmlFor={id}>Username</label>
<input
id={id}
value={value}
autoComplete="username"
aria-invalid={status === 'taken' ? true : undefined}
aria-describedby={`${id}-msg`}
onChange={(e) => setValue(e.target.value)}
/>
{status === 'checking' && <span aria-hidden="true">Checking...</span>}
{/* Always mounted, so the browser registers it as a live region before its text changes. */}
<p id={`${id}-msg`} role="status">{MESSAGES[status](value)}</p>
</div>
);
}
The real request function
This is the check that the component receives. It was run against a small local server (the same file starts one), so the abort and the HTTP 500 handling are exercised:
import http from 'node:http';
import assert from 'node:assert/strict';
// The function the component receives as `check`.
export async function checkUsername(name, signal) {
const res = await fetch(`http://localhost:4010/api/username-taken?name=${encodeURIComponent(name)}`, { signal });
if (!res.ok) throw new Error(`availability check failed with HTTP ${res.status}`); // fetch resolves on 404/500: turn them into failures
const body = await res.json();
return body.taken === true;
}
// A small server: "admin" is taken, "slow" answers after 2 s, "broken" returns 500.
const server = http.createServer((req, res) => {
const name = new URL(req.url, 'http://x').searchParams.get('name');
const reply = () => {
if (name === 'broken') { res.statusCode = 500; res.end('oops'); return; }
res.setHeader('content-type', 'application/json');
res.end(JSON.stringify({ taken: name === 'admin' }));
};
name === 'slow' ? setTimeout(reply, 2000) : reply();
});
await new Promise((r) => server.listen(4010, r));
console.log('admin ->', await checkUsername('admin', new AbortController().signal));
console.log('maria ->', await checkUsername('maria', new AbortController().signal));
await assert.rejects(checkUsername('broken', new AbortController().signal), /HTTP 500/);
console.log('broken -> rejected with HTTP 500');
const ctrl = new AbortController();
const pending = checkUsername('slow', ctrl.signal);
setTimeout(() => ctrl.abort(), 50);
await assert.rejects(pending, (e) => e.name === 'AbortError');
console.log('slow -> aborted after 50 ms, rejected with AbortError');
server.closeAllConnections();
server.close();
Run in a node:22 container (node async/check-username.mjs) it printed:
admin -> true
maria -> false
broken -> rejected with HTTP 500
slow -> aborted after 50 ms, rejected with AbortError
Tests with a controllable server
The tests replace the network with a fake whose answers the test resolves by hand, in any order. They use the jsdom setup file dom-env.mjs, listed under Running the code at the end.
import '../dom-env.mjs';
import assert from 'node:assert/strict';
import { render, screen, cleanup, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { UsernameField } from './UsernameField.tsx';
const user = userEvent.setup({ delay: null }); // type without pauses, as fast as a pasted burst
const sleep = (ms: number) => new Promise((r) => setTimeout(r, ms));
type Call = { name: string; signal: AbortSignal; resolve: (taken: boolean) => void; reject: (e: unknown) => void };
let calls: Call[] = [];
const fakeServer = (honourAbort: boolean) => (name: string, signal: AbortSignal) =>
new Promise<boolean>((resolve, reject) => {
calls.push({ name, signal, resolve, reject });
if (honourAbort) signal.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')));
});
const status = () => screen.getByRole('status').textContent;
async function typeAndSettle(text: string, props: Partial<Parameters<typeof UsernameField>[0]> = {}, honourAbort = false) {
cleanup();
calls = [];
render(<UsernameField check={fakeServer(honourAbort)} delay={40} {...props} />);
const input = screen.getByLabelText('Username');
await user.type(input, text);
return input;
}
// 1. A burst of typing sends one request, for the final value.
await typeAndSettle('abcd');
await waitFor(() => assert.equal(calls.length, 1));
assert.equal(calls[0].name, 'abcd');
console.log('1 typed "abcd" in one burst -> requests sent:', calls.length, '| for', JSON.stringify(calls[0].name));
// 2. Out-of-order answers: the answer for the OLD value arrives last and must be ignored.
let input = await typeAndSettle('abcd');
await waitFor(() => assert.equal(calls.length, 1)); // request for "abcd" is in flight
await user.type(input, 'e'); // value is now "abcde"
await waitFor(() => assert.equal(calls.length, 2));
assert.equal(calls[0].signal.aborted, true);
calls[1].resolve(false); // newer answer first: available
await waitFor(() => assert.equal(status(), 'abcde is available.'));
calls[0].resolve(true); // older answer arrives late: "abcd is taken"
await sleep(30);
assert.equal(status(), 'abcde is available.');
assert.equal(input.getAttribute('aria-invalid'), null);
console.log('2 late answer for "abcd" (taken) after "abcde" (available):', JSON.stringify(status()));
// 3. Control: with the stale-answer guard switched off, the same sequence shows the wrong result.
input = await typeAndSettle('abcd', { ignoreStale: false });
await waitFor(() => assert.equal(calls.length, 1));
await user.type(input, 'e');
await waitFor(() => assert.equal(calls.length, 2));
calls[1].resolve(false);
await waitFor(() => assert.equal(status(), 'abcde is available.'));
calls[0].resolve(true);
await waitFor(() => assert.notEqual(status(), 'abcde is available.'));
console.log('3 control without the guard:', JSON.stringify(status()), '| the field holds', JSON.stringify((input as HTMLInputElement).value), '(the stale answer won)');
// 4. Taken: the field is marked invalid and described by the live-region message.
input = await typeAndSettle('admin');
await waitFor(() => assert.equal(calls.length, 1));
calls[0].resolve(true);
await waitFor(() => assert.equal(input.getAttribute('aria-invalid'), 'true'));
assert.equal(document.getElementById(input.getAttribute('aria-describedby')!)!.textContent, 'admin is already taken. Try another username.');
console.log('4 taken ->', JSON.stringify(status()));
// 5. The check itself fails: fail open, no invalid state, a neutral message.
input = await typeAndSettle('admin');
await waitFor(() => assert.equal(calls.length, 1));
calls[0].reject(new TypeError('network down'));
await waitFor(() => assert.match(status()!, /could not check availability/));
assert.equal(input.getAttribute('aria-invalid'), null);
console.log('5 network failure ->', JSON.stringify(status()), '| aria-invalid:', input.getAttribute('aria-invalid'));
// 6. A request aborted because the user kept typing rejects with AbortError; that must not show the failure message.
input = await typeAndSettle('abcd', {}, true);
await waitFor(() => assert.equal(calls.length, 1));
await user.type(input, 'e');
await waitFor(() => assert.equal(calls.length, 2));
await sleep(30);
assert.doesNotMatch(status()!, /could not check/);
console.log('6 aborted request rejected with AbortError -> status text:', JSON.stringify(status()));
// 7. Names that cannot be valid send nothing.
await typeAndSettle('ab!');
await sleep(80);
assert.equal(calls.length, 0);
console.log('7 typed "ab!" -> requests sent:', calls.length);
Run in a node:22 container (node --import tsx async/async.test.tsx, React 18.3.1), it printed:
1 typed "abcd" in one burst -> requests sent: 1 | for "abcd"
2 late answer for "abcd" (taken) after "abcde" (available): "abcde is available."
3 control without the guard: "abcde is already taken. Try another username." | the field holds "abcde" (the stale answer won)
4 taken -> "admin is already taken. Try another username."
5 network failure -> "We could not check availability right now. You can continue; we will check again when you submit." | aria-invalid: null
6 aborted request rejected with AbortError -> status text: ""
7 typed "ab!" -> requests sent: 0
Reading the output: line 6 prints an empty string on purpose, because the correct text for an aborted request is no text at all (the checking state keeps the region quiet, and an abort must not be reported as a failure); line 1 shows one request for a burst of typing; line 2 shows the late "taken" answer for abcd being ignored after abcde was found available; line 3 is the control, with the stale-answer guard switched off, where the same sequence leaves the wrong result on screen for the current value, which proves the guard is what makes line 2 pass; line 5 shows the fail-open message; line 6 shows an aborted request producing no message; line 7 shows no request for an invalid name. tsc --noEmit on these files reports no errors.
Choices and pitfalls
- Abort and ignore are both needed. Aborting saves bandwidth and server work, but a response can still arrive after abort in some code paths (or the check function may not honour the signal), so the code also checks
signal.abortedafter theawait. A common alternative is comparing the response's value with the current value; the signal check is simpler and does not need a ref. - Debounce length trades responsiveness against load: 300 ms is a common starting point, tuned against how fast users type and how costly the endpoint is. The cap on load is also the server's job (rate limiting), because debouncing is a client courtesy.
- Check on blur instead when the endpoint is expensive or the rule is rarely violated; it removes the race entirely at the cost of later feedback.
- Do not trust the check at submit. The authoritative uniqueness test is the server's insert (a unique constraint), whose error is mapped back to the field.
- User enumeration. A public "is this name taken" endpoint tells attackers which accounts exist; for email addresses prefer to tell the user only after submit, and rate-limit either way.
Running the code
Everything runs from one project root in a node:22 container. Files: dom-env.mjs, package.json, tsconfig.json and async/UsernameField.tsx, async/async.test.tsx and async/check-username.mjs (the component, the tests and the request function above).
npm i react@18.3.1 react-dom@18.3.1 @testing-library/react@16 @testing-library/dom@10 @testing-library/user-event@14 jsdom@25 tsx typescript@5 @types/react@18 @types/react-dom@18 @types/node@22
node --import tsx async/async.test.tsx
node async/check-username.mjs
npx tsc --noEmit
dom-env.mjs (copies the jsdom window's globals onto Node's global object):
import { JSDOM } from 'jsdom';
const { window } = new JSDOM('<!doctype html><body></body>', { url: 'http://localhost/', pretendToBeVisual: true });
for (const k of Object.getOwnPropertyNames(window)) if (!(k in globalThis)) Object.defineProperty(globalThis, k, { configurable: true, get: () => window[k] });
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
package.json:
{ "type": "module" }
tsconfig.json:
{"compilerOptions":{"jsx":"react-jsx","strict":true,"module":"esnext","moduleResolution":"bundler","target":"es2022","allowImportingTsExtensions":true,"noEmit":true,"skipLibCheck":true}}
Without "type": "module" the test does not compile (esbuild, used by tsx, reports Top-level await is currently not supported with the "cjs" output format); without "jsx": "react-jsx" the JSX becomes React.createElement calls and the run stops with ReferenceError: React is not defined.
Build a registration form with client-side validation in plain HTML and JavaScript that works for screen reader and keyboard users: invalid fields are flagged, each error is tied to its input, focus goes to the first problem on a failed submit, and the form-level result is announced. Show the markup and the essential script.
Sample Answer
Direct answer
Switch the browser's own bubbles off with novalidate on the form, keep the constraint attributes (required, type="email", minlength) as the rule source, and read the results from each control's validity object. On blur and on submit, write a message into a <p> next to the field, link it to the input with aria-describedby, and set aria-invalid="true". On a failed submit call preventDefault(), focus the first invalid control in document order, and put a one-line result ("The form was not submitted. 3 fields need attention.") into a role="status" element that was already on the page. Style invalid fields from the ARIA state (or :user-invalid), not from :invalid, so untouched fields are not flagged on page load.
Markup and script
Terms used below: the constraint attributes are the HTML attributes that declare a rule (required, type="email", minlength); the browser checks them and records the result on each control's validity object, whose flags (valueMissing, typeMismatch, tooShort) say which rule failed; willValidate is true for a control that takes part in that checking; focusout is the event fired when focus leaves an element, and unlike blur it bubbles up to ancestors, so one listener on the form catches every field; :user-invalid is a CSS pseudo-class (a selector for an element state) that matches a failing control only after the user has interacted with it.
One file: the markup, the style rules and the essential script together.
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Create account</title>
<style>
.error { color: #b00020; margin: .25rem 0 0; }
input[aria-invalid="true"] { border: 2px solid #b00020; }
input:focus-visible { outline: 3px solid #1a56db; outline-offset: 2px; }
</style>
</head>
<body>
<form id="register" action="/register" method="post" novalidate>
<h1>Create account</h1>
<div>
<label for="name">Full name</label>
<input id="name" name="name" autocomplete="name" required>
<p class="error" id="name-error" hidden></p>
</div>
<div>
<label for="email">Email</label>
<input id="email" name="email" type="email" autocomplete="email" required>
<p class="error" id="email-error" hidden></p>
</div>
<div>
<label for="password">Password (at least 8 characters)</label>
<input id="password" name="password" type="password" autocomplete="new-password" required minlength="8">
<p class="error" id="password-error" hidden></p>
</div>
<div>
<input id="terms" name="terms" type="checkbox" required>
<label for="terms">I accept the terms</label>
<p class="error" id="terms-error" hidden></p>
</div>
<button type="submit">Create account</button>
<p id="form-status" role="status"></p>
</form>
<script>
const form = document.getElementById('register');
const formStatus = document.getElementById('form-status');
const MISSING = {
name: 'Enter your full name',
email: 'Enter your email address',
password: 'Enter a password',
terms: 'Accept the terms to continue',
};
// Turn the browser's own constraint results into our wording (browser messages differ by browser and language).
function messageFor(input) {
const v = input.validity;
if (v.valid) return '';
if (v.valueMissing) return MISSING[input.name];
if (v.typeMismatch) return 'Enter an email address like name@example.com';
if (v.tooShort) return `Password must be at least ${input.minLength} characters`;
return input.validationMessage;
}
function setError(input, message) {
const error = document.getElementById(`${input.id}-error`);
if (message) {
error.textContent = message;
error.hidden = false;
input.setAttribute('aria-invalid', 'true');
input.setAttribute('aria-describedby', error.id);
} else {
error.hidden = true;
error.textContent = '';
input.removeAttribute('aria-invalid');
input.removeAttribute('aria-describedby');
}
}
const fields = [...form.elements].filter((el) => el.willValidate && el.matches('input, select, textarea')); // willValidate is true for buttons too, so the matches() filter removes them
// Showing an error on blur adds a line of text and pushes the submit button down. If that happens
// between mouse-down and mouse-up on the button, the click is lost. So while a pointer is held on
// the submit button, leaving a field shows nothing; the submit handler validates everything anyway.
let pressingSubmit = false;
const submitButton = form.querySelector('button[type="submit"]');
const release = () => { pressingSubmit = false; };
submitButton.addEventListener('pointerdown', () => { pressingSubmit = true; });
submitButton.addEventListener('pointerup', release);
submitButton.addEventListener('pointerleave', release);
submitButton.addEventListener('pointercancel', release);
// Leaving a field shows its error; once it shows one, every edit re-checks it.
form.addEventListener('focusout', (e) => {
if (!pressingSubmit && fields.includes(e.target)) setError(e.target, messageFor(e.target));
});
form.addEventListener('input', (e) => {
if (e.target.hasAttribute('aria-invalid')) setError(e.target, messageFor(e.target));
});
form.addEventListener('change', (e) => {
if (e.target.type === 'checkbox' && e.target.hasAttribute('aria-invalid')) setError(e.target, messageFor(e.target));
});
form.addEventListener('submit', (e) => {
e.preventDefault(); // nothing is sent while anything is wrong; we decide when to send
fields.forEach((input) => setError(input, messageFor(input)));
const invalid = fields.filter((input) => !input.validity.valid);
if (invalid.length) {
invalid[0].focus(); // first problem, in DOM order
formStatus.textContent = invalid.length === 1
? 'The form was not submitted. 1 field needs attention.'
: `The form was not submitted. ${invalid.length} fields need attention.`;
return;
}
formStatus.textContent = 'Account created.';
// here: fetch('/register', { method: 'POST', body: new FormData(form) })
});
</script>
</body>
</html>
Choices that matter:
- Error tied to its input. Every input has a
<label for>(its accessible name) and, only while invalid, anaria-describedbypointing at its<p class="error">. A screen reader reads the label, then the description, when the field gets focus. Removing the attribute when the error clears stops stale text being read. aria-invalidis set only after the user has left the field or tried to submit, and removed when fixed. MDN advises against marking empty required fields invalid before the user has had a chance to fill them in.- Native constraints, custom wording.
novalidatesuppresses the browser bubbles, which differ by browser and language and cannot be styled (MDN).validity.valueMissing,typeMismatchandtooShortstill tell us which rule failed, so the page picks its own message. MDN definestooShortas true for a value shorter thanminlengthafter the user has edited it, which is the case for a typed password. fieldsfilter.form.elementsincludes the submit button, which also counts as a validation candidate; filtering toinput, select, textareastops the script from looking for an error element that does not exist.- A click must survive the first error. Showing an error on blur inserts a line of text above the submit button. When the user types a bad value and then clicks Submit, the pointer goes down on the button (the field blurs and its error appears), the button moves down about 22 to 25 px, and the pointer is released over something else, so no click happens. Measured in Playwright 1.48.2: without the guard, one click on Submit after typing
abcinto Email did nothing in Chromium, Firefox and WebKit. ThepressingSubmitflag, set onpointerdownand cleared onpointerup,pointerleaveandpointercancel, makes the blur skip its error while the button is held; the submit handler validates every field anyway. - Focus.
invalid[0].focus()moves to the first problem in DOM order. Focusing it makes a screen reader read its label and its error description. - Form-level result.
<p id="form-status" role="status">is in the HTML from the start and only its text changes, which is what live regions need (MDN: announcements come from content changes in an existing region). It is a polite region, so it does not interrupt the field announcement. Exact speech output differs between screen readers and has to be checked by hand with NVDA, JAWS and VoiceOver; the automated run below proves the markup and the focus, not the wording a particular screen reader speaks. - No navigation on failure.
preventDefault()on thesubmitevent cancels the default action (the submission), but does not stop the event propagating (travelling on to listeners on ancestor elements), which is a separate method (stopPropagation()).
Styling invalid state: :invalid, :user-invalid or ARIA
| Selector | Matches | Use |
|---|---|---|
:invalid | Any control failing a constraint, from the moment the page loads | Not for visual error styling: every empty required field would be red before the user types |
:user-invalid | A failing control only after the user has interacted with it (MDN: Baseline widely available since November 2023) | Good CSS-only option when you have no script |
[aria-invalid="true"] | What the script decided | Used here, because the same state also drives the message and the screen reader |
The red border is paired with visible message text, so the error does not depend on colour alone. The focus ring uses :focus-visible.
Run
The check below loads the file above in Chromium, Firefox and WebKit (Playwright 1.48.2; WebKit here is not Safari on iOS) and asserts: nothing is flagged on load although :invalid already matches 4 controls and :user-invalid matches 0; an empty submit does not navigate, focuses Full name, flags 4 fields and sets the status; a partly valid submit focuses Email (the first invalid field, not the first field), and the valid Full name stays unflagged; fixing the email clears its error as the user types; a fully valid submit reports success with no errors left; :user-invalid matches the email field only after the user typed a bad address and tabbed away; and one real mouse click on Submit, made while a field with a bad value still has focus, runs the submit handler and focuses Full name.
import { chromium, firefox, webkit } from 'playwright';
import { readFileSync } from 'node:fs';
import assert from 'node:assert/strict';
const html = readFileSync(new URL('./register.html', import.meta.url), 'utf8');
const fail = [];
const check = (label, fn) => { try { fn(); } catch (e) { fail.push(label + ': ' + e.message.split('\n')[0]); } };
for (const [name, type] of [['chromium', chromium], ['firefox', firefox], ['webkit', webkit]]) {
const browser = await type.launch();
const page = await browser.newPage();
page.on('pageerror', (e) => fail.push(name + ' pageerror: ' + e.message));
await page.goto('data:text/html;charset=utf-8,' + encodeURIComponent(html));
const url0 = page.url();
const q = (sel) => page.evaluate((s) => document.querySelectorAll(s).length, sel);
// 1. Untouched form: no errors anywhere, although CSS :invalid already matches the required fields.
const load = { invalid: await q('input:invalid'), userInvalid: await q('input:user-invalid'), ariaInvalid: await q('[aria-invalid]'), visibleErrors: await q('.error:not([hidden])') };
check('load', () => assert.deepEqual(load, { invalid: 4, userInvalid: 0, ariaInvalid: 0, visibleErrors: 0 }));
// 2. Empty submit
await page.click('button');
const emptyRun = await page.evaluate(() => ({
active: document.activeElement.id,
status: document.getElementById('form-status').textContent,
described: [...document.querySelectorAll('[aria-invalid]')].map((i) => [i.id, document.getElementById(i.getAttribute('aria-describedby')).textContent]),
unchanged: location.href,
}));
check('empty submit focus', () => assert.equal(emptyRun.active, 'name'));
check('empty submit status', () => assert.equal(emptyRun.status, 'The form was not submitted. 4 fields need attention.'));
check('empty submit errors', () => assert.deepEqual(emptyRun.described, [['name', 'Enter your full name'], ['email', 'Enter your email address'], ['password', 'Enter a password'], ['terms', 'Accept the terms to continue']]));
check('no navigation', () => assert.equal(emptyRun.unchanged, url0));
const nameBox = await page.getByRole('textbox', { name: 'Full name' }).evaluate((el) => ({ border: getComputedStyle(el).borderTopWidth + ' ' + getComputedStyle(el).borderTopColor }));
check('invalid styling applied', () => assert.equal(nameBox.border, '2px rgb(176, 0, 32)'));
// 3. Partly valid: focus lands on the FIRST invalid field, not the first field
await page.fill('#name', 'Ada Lovelace');
await page.fill('#email', 'abc');
await page.fill('#password', 'short');
await page.click('button');
const partialRun = await page.evaluate(() => ({
active: document.activeElement.id,
nameInvalid: document.getElementById('name').hasAttribute('aria-invalid'),
email: document.getElementById('email-error').textContent,
password: document.getElementById('password-error').textContent,
status: document.getElementById('form-status').textContent,
}));
check('first invalid focus', () => assert.equal(partialRun.active, 'email'));
check('valid field cleared', () => assert.equal(partialRun.nameInvalid, false));
check('email message', () => assert.equal(partialRun.email, 'Enter an email address like name@example.com'));
check('password message', () => assert.equal(partialRun.password, 'Password must be at least 8 characters'));
check('status 3', () => assert.equal(partialRun.status, 'The form was not submitted. 3 fields need attention.'));
// 4. Fixing a field clears its error without a blur, then a full valid submit succeeds
await page.fill('#email', 'ada@example.com');
const cleared = await page.evaluate(() => document.getElementById('email').hasAttribute('aria-invalid'));
check('email cleared on input', () => assert.equal(cleared, false));
await page.fill('#password', 'correct horse');
await page.check('#terms');
await page.click('button');
const validRun = await page.evaluate(() => ({ status: document.getElementById('form-status').textContent, errors: document.querySelectorAll('.error:not([hidden])').length, aria: document.querySelectorAll('[aria-invalid]').length }));
check('success', () => assert.deepEqual(validRun, { status: 'Account created.', errors: 0, aria: 0 }));
// 5. :user-invalid appears only after interaction
await page.goto('data:text/html;charset=utf-8,' + encodeURIComponent(html + '<!-- fresh -->')); // fresh page: a reload would restore typed values in Firefox
await page.click('#email'); await page.keyboard.type('abc'); await page.keyboard.press('Tab');
const userInvalidRun = await page.evaluate(() => ({ email: document.getElementById('email').matches(':user-invalid'), name: document.getElementById('name').matches(':user-invalid') }));
check(':user-invalid after interaction', () => assert.deepEqual(userInvalidRun, { email: true, name: false }));
// 6. One real click on Submit while a field with a bad value still has focus (its error is not shown yet)
await page.goto('data:text/html;charset=utf-8,' + encodeURIComponent(html + '<!-- click -->'));
await page.click('#email'); await page.keyboard.type('abc');
await page.click('button');
const clickRun = await page.evaluate(() => ({ active: document.activeElement.id, status: document.getElementById('form-status').textContent }));
check('one click submits', () => assert.deepEqual(clickRun, { active: 'name', status: 'The form was not submitted. 4 fields need attention.' }));
console.log(name, fail.length ? 'FAIL' : 'ok', JSON.stringify({ load, afterEmptySubmit: { focus: emptyRun.active, status: emptyRun.status }, afterPartial: { focus: partialRun.active, status: partialRun.status }, userInvalidAfterTypingBadEmailAndTab: userInvalidRun, oneClickAfterBadEmail: clickRun }));
await browser.close();
}
if (fail.length) { console.log(fail.join('\n')); process.exit(1); }
console.log('ALL CHECKS PASSED in chromium, firefox, webkit');
Saved next to register.html and run with node check.mjs (after npm i playwright@1.48.2) in the Playwright container image, it prints one ok line per browser, ending with ALL CHECKS PASSED in chromium, firefox, webkit. Deleting the invalid[0].focus() line makes the focus checks fail in all three browsers, and deleting !pressingSubmit && from the focusout listener makes the one-click check fail in all three (the status stays empty and focus stays on the Submit button instead of moving to Full name).
Reading the script: check(label, fn) runs an assertion and records a failure message instead of stopping, so one run reports every broken expectation. q(sel) counts the elements matching a CSS selector inside the page. The data:text/html URL loads the HTML string directly, so no web server is needed. getComputedStyle reads the border the browser actually applied, which proves the aria-invalid rule styles the field (2px, rgb(176, 0, 32) is the #b00020 red). Step 5 opens a fresh page rather than reloading because Firefox can restore typed values on reload, which would hide the "untouched" state.
Trade-offs
- Focus the first invalid field versus an error summary: one field-focus move is enough for a short form like this; a long form benefits from a summary with links, since the first invalid field can be far from the submit button.
role="status"versusrole="alert":alertis assertive and, per MDN, should be used sparingly; polite status is right for a count that follows a focus move.- Pitfalls: an error that appears on blur above the submit button and swallows the first click; pointing
aria-describedbyat an element that does not exist; leavingaria-describedbyon after the error clears; re-using nativevalidationMessagetext, which differs between browsers; shipping client validation without the same rules on the server.
You are building a multi-step sign-up form with inline validation. How do you implement the labels, inline error messages, focus order and ARIA roles so the form works with a screen reader and with the keyboard alone across every step, and how do you announce a step's errors to assistive technology?
Sample Answer
Direct answer
Make every control carry a real <label>, tie each error message to its field with aria-invalid and aria-describedby, and treat each step change as a navigation event for assistive technology (AT, such as a screen reader): after every "Next" or "Back" move keyboard focus to the new step's heading. When validation fails, show a summary of the errors at the top of the step and move focus to it; the summary's links jump to the offending fields. Keep the DOM order identical to the visual order so the Tab key walks the form top to bottom without any tabindex greater than 0.
How each requirement is met
| Requirement | Implementation |
|---|---|
| Labels | <label htmlFor> pointing at the input id (generated with React's useId so ids stay unique). Placeholder text is never the label. Clicking the label focuses the input. |
| Inline error messages | A <p id="...-err"> rendered next to the field only when the field has an error, referenced by aria-describedby, plus aria-invalid="true" on the input. |
| When errors appear | Not while the user is still typing a first value. Errors are revealed on a "Next" attempt (and clear as soon as the value becomes valid). MDN advises not setting aria-invalid="true" on empty required fields until a submit attempt, because the user may still be filling them in. |
| Focus order | Native elements in DOM order: fields, then "Back", then "Next". Only form controls and links are focusable, so the Tab key needs no custom handling. |
| ARIA roles | Few are needed: native <form>, <label>, <input>, <button>, <h2> already have the right semantics. ARIA is added in exactly five places: aria-invalid and aria-describedby on a field with a visible error, aria-labelledby on the form (so it is named by the step heading), role="alert" on the error summary, and role="status" on the region for the final success message. |
| Moving between steps | The <h2> for the step has tabIndex={-1} (focusable by script, not in the Tab sequence). After a successful step change the app calls .focus() on it, so the screen reader reads "Step 2 of 2: Profile" and the next Tab lands on the first field of the step. Without this, focus stays on the submit button (in this component the same element, relabelled "Create account" on the last step; in a wizard that swaps its buttons it would be a removed element and focus would fall back to the page), and the screen reader user is never told that the step changed. |
| Announcing a step's errors | On a failed "Next", focus moves to an error summary container (tabIndex={-1}) that contains a role="alert" element listing the problems; each item is a link to the field. This is the pattern the GOV.UK Design System documents: it says to move keyboard focus to the error summary, and its summary puts role="alert" on an element nested inside the focused root. |
| Keyboard alone | Everything is a button, link or input. Enter in a text field submits the form (the "Next" button is the form's default submit button). Summary links call .focus() on the field and preventDefault() so the page does not jump or change the URL. |
Two choices worth defending in the room: (1) step titles are announced through focus on the heading, not through a second aria-live region, because focus plus a live region carrying the same text risks the screen reader speaking it twice; (2) the form uses noValidate (an attribute that switches off the browser's built-in validation) so the app, not the browser's popup bubbles, owns the error text, the summary and the focus.
A live region is an element a screen reader watches: when its text changes, the reader speaks the new text without keyboard focus moving. role="alert", role="status" and the aria-live attribute create one; alert is assertive (it interrupts what is being read) and status is polite (it waits for a pause). That is why the same words must not arrive twice, once through a focused heading and once through a live region: the user would hear them twice.
Worked example: a two-step sign-up
Step 1 collects email and password, step 2 collects a name. This component was rendered under React 18 and jsdom (a simulated browser DOM) in a node:22 container with Testing Library, and the test drives it with simulated user events. The file dom-env.mjs, listed under Running the code at the end, creates the browser-like environment: it copies the jsdom window's globals (document, window, Event and so on) onto Node's global object so React and Testing Library can run. The form itself does not depend on it.
The component:
import { useId, useRef, useState, useEffect, type FormEvent } from 'react';
type Values = { email: string; password: string; name: string };
type Errors = Partial<Record<keyof Values, string>>;
const STEPS = [
{ title: 'Account', fields: ['email', 'password'] as const },
{ title: 'Profile', fields: ['name'] as const },
];
function validate(v: Values): Errors {
const e: Errors = {};
if (!/^\S+@\S+\.\S+$/.test(v.email)) e.email = 'Enter an email address like name@example.com.';
if (v.password.length < 8) e.password = 'Password must be at least 8 characters.';
if (!v.name.trim()) e.name = 'Enter your name.';
return e;
}
const LABELS: Record<keyof Values, string> = { email: 'Email', password: 'Password', name: 'Full name' };
export function SignupWizard({ manageFocus = true, onDone }: { manageFocus?: boolean; onDone?: (v: Values) => void }) {
const uid = useId();
const [step, setStep] = useState(0);
const [values, setValues] = useState<Values>({ email: '', password: '', name: '' });
const [shown, setShown] = useState<Errors>({}); // errors the user has earned the right to see
const [announcement, setAnnouncement] = useState('');
const summaryRef = useRef<HTMLDivElement>(null);
const headingRef = useRef<HTMLHeadingElement>(null);
const focusTarget = useRef<'summary' | 'heading' | null>(null);
const current = STEPS[step];
const all = validate(values);
const stepErrors = Object.fromEntries(current.fields.filter((f) => all[f]).map((f) => [f, all[f]])) as Errors;
const errorKeys = Object.keys(shown) as (keyof Values)[];
// Focus moves after the DOM for the new state exists.
useEffect(() => {
if (!manageFocus) return;
if (focusTarget.current === 'summary') summaryRef.current?.focus();
if (focusTarget.current === 'heading') headingRef.current?.focus();
focusTarget.current = null;
});
function next(e: FormEvent) {
e.preventDefault();
if (Object.keys(stepErrors).length) {
setShown(stepErrors);
setAnnouncement('');
focusTarget.current = 'summary';
return;
}
setShown({});
if (step === STEPS.length - 1) {
onDone?.(values);
setAnnouncement('Account created.');
return;
}
setStep(step + 1);
focusTarget.current = 'heading';
}
function back() {
setShown({});
setStep(step - 1);
focusTarget.current = 'heading';
}
return (
<form onSubmit={next} noValidate aria-labelledby={`${uid}-h`}>
<div role="status" data-testid="announcer">{announcement}</div>
<h2 id={`${uid}-h`} tabIndex={-1} ref={headingRef}>
Step {step + 1} of {STEPS.length}: {current.title}
</h2>
{errorKeys.length > 0 && (
<div ref={summaryRef} tabIndex={-1} data-testid="summary">
<div role="alert">
<p>
{errorKeys.length === 1 ? 'There is 1 problem' : `There are ${errorKeys.length} problems`}
</p>
<ul>
{errorKeys.map((k) => (
<li key={k}>
<a
href={`#${uid}-${k}`}
onClick={(ev) => {
ev.preventDefault();
document.getElementById(`${uid}-${k}`)?.focus();
}}
>
{shown[k]}
</a>
</li>
))}
</ul>
</div>
</div>
)}
{current.fields.map((k) => {
const id = `${uid}-${k}`;
const err = shown[k];
return (
<div key={k}>
<label htmlFor={id}>{LABELS[k]}</label>
<input
id={id}
name={k}
type={k === 'password' ? 'password' : k === 'email' ? 'email' : 'text'}
autoComplete={k === 'password' ? 'new-password' : k === 'email' ? 'email' : 'name'}
value={values[k]}
aria-invalid={err ? true : undefined}
aria-describedby={err ? `${id}-err` : undefined}
onChange={(ev) => {
const v = { ...values, [k]: ev.target.value };
setValues(v);
// an already-shown error clears the moment the value becomes valid
if (shown[k] && !validate(v)[k]) setShown(({ [k]: _gone, ...rest }) => rest);
}}
/>
{err && <p id={`${id}-err`}>{err}</p>}
</div>
);
})}
{step > 0 && <button type="button" onClick={back}>Back</button>}
<button type="submit">{step === STEPS.length - 1 ? 'Create account' : 'Next'}</button>
</form>
);
}
How the focus and error logic reads. A handler cannot call .focus() straight after setStep, because the element to focus (the summary, or the next step's heading) does not exist until React has re-rendered. So the handler records the destination in focusTarget.current (a ref, which can change without causing a render), and the useEffect with no dependency list runs after every render, focuses the recorded element and clears the ref. Traced with both steps:
- Next clicked on step 1 with empty fields:
stepErrorshas two entries,setShownstores them,focusTargetbecomes'summary', the render draws the summary, the effect focuses it. - Next clicked with a valid email and an 8-plus-character password:
stepErrorsis empty,shownis cleared,setStep(1)runs,focusTargetbecomes'heading', the render shows "Step 2 of 2: Profile", the effect focuses that<h2>.
Three idioms in the code: Partial<Record<keyof Values, string>> is an object whose keys are the field names and whose values are optional strings; as const on the fields arrays makes TypeScript treat them as fixed lists of exact names, so all[f] is checked; and setShown(({ [k]: _gone, ...rest }) => rest) receives the current errors object, pulls out the entry named by k (the unused _gone) and returns a copy of the rest, so one field's error is removed without touching the others.
The test (numbered checks 1 to 4, with 2b, each check one requirement, check 5 is a control; emptyNext renders the form and clicks Next with empty fields):
import '../dom-env.mjs';
import assert from 'node:assert/strict';
import { render, screen, cleanup } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { SignupWizard } from './SignupWizard.tsx';
const user = userEvent.setup();
const active = () => document.activeElement as HTMLElement;
async function emptyNext(manageFocus = true) {
render(<SignupWizard manageFocus={manageFocus} />);
await user.click(screen.getByRole('button', { name: 'Next' }));
}
// 1. Invalid Next: errors listed, focus moves to the summary, fields are wired to their messages.
await emptyNext();
assert.equal(active(), screen.getByTestId('summary'));
assert.ok(active().querySelector('[role=alert]'));
assert.match(active().textContent!, /There are 2 problems/);
const email = screen.getByLabelText('Email');
assert.equal(email.getAttribute('aria-invalid'), 'true');
const msg = document.getElementById(email.getAttribute('aria-describedby')!)!;
assert.equal(msg.textContent, 'Enter an email address like name@example.com.');
console.log('1 invalid Next: focus on the error summary containing role=alert', '| email described by:', msg.textContent);
// 2. A summary link moves focus to the field.
await user.click(screen.getByRole('link', { name: /at least 8/ }));
assert.equal(active(), screen.getByLabelText('Password'));
console.log('2 summary link focuses:', (active() as HTMLInputElement).name);
// 2b. Enter inside a text field submits through the form's Next button.
await user.type(screen.getByLabelText('Email'), '{Enter}');
assert.equal(active(), screen.getByTestId('summary'));
console.log('2b Enter in a field submitted the form: focus on the summary again');
// 3. Fixing a value clears its error; valid Next moves focus to the new step heading.
await user.type(screen.getByLabelText('Email'), 'a@b.co');
assert.equal(screen.getByLabelText('Email').getAttribute('aria-invalid'), null);
await user.type(screen.getByLabelText('Password'), 'longenough');
await user.click(screen.getByRole('button', { name: 'Next' }));
assert.equal(active().tagName, 'H2');
assert.equal(active().textContent, 'Step 2 of 2: Profile');
console.log('3 step 2: focus on <h2>', JSON.stringify(active().textContent));
// 4. Back keeps what was typed.
await user.click(screen.getByRole('button', { name: 'Back' }));
assert.equal((screen.getByLabelText('Email') as HTMLInputElement).value, 'a@b.co');
console.log('4 back: email still', (screen.getByLabelText('Email') as HTMLInputElement).value);
// 5. Control: the same check against a build without focus management must FAIL.
cleanup();
await emptyNext(false);
assert.notEqual(active(), screen.getByTestId('summary'));
console.log('5 control (no focus management): focus stayed on', active().tagName, '(assertion 1 would fail here)');
Run in a node:22 container with node --import tsx wizard/wizard.test.tsx (React 18.3.1, Testing Library 16, jsdom 25), it prints:
1 invalid Next: focus on the error summary containing role=alert | email described by: Enter an email address like name@example.com.
2 summary link focuses: password
2b Enter in a field submitted the form: focus on the summary again
3 step 2: focus on <h2> "Step 2 of 2: Profile"
4 back: email still a@b.co
5 control (no focus management): focus stayed on BUTTON (assertion 1 would fail here)
The process exits 0 only if every assert passes, and check 5 renders the same form with focus management switched off to show that the focus assertion does fail without it. tsc --noEmit on the same files reports no type errors.
What this does not prove, and how to cover it
jsdom checks the DOM wiring (names, descriptions, focus target, order), not what a particular screen reader says. Confirm the spoken result by hand with at least one desktop pairing (for example NVDA, a free Windows screen reader, with Firefox or Chrome, or VoiceOver, the one built into macOS, with Safari) and by tabbing through the form with the mouse unplugged. The manual pass is the essential one. A cheap addition is an automated rules check such as axe-core (an open-source engine that scans a rendered page for accessibility rule violations) in the end-to-end suite, which catches missing labels and invalid ARIA.
Trade-offs and pitfalls
- Inline error vs summary. Inline messages sit next to the problem; the summary gives one place to hear all problems at once after a failed "Next". Use both. The summary alone forces users to remember messages; inline alone leaves a screen reader user on the button with no news.
role="alert"on every inline error makes several messages interrupt each other when a step has multiple failures. Keep the alert on the single summary.- Validating every keystroke announces "invalid" while the user is mid-word. Validate on "Next" and clear errors on the keystroke that fixes them (as the component does); if earlier feedback is wanted, also validate on blur after the first attempt, which this component does not do.
- Removing fields from the DOM between steps loses their values unless the values live in the parent's state, as here, so "Back" restores them.
- Color-only errors fail users who cannot see color; the message text is the signal and the red border is decoration.
- Disabled "Next" until valid hides why the form cannot proceed; leave it enabled and explain.
Running the code
Everything runs from one project root in a node:22 container. Files: dom-env.mjs, package.json, tsconfig.json and wizard/SignupWizard.tsx and wizard/wizard.test.tsx (the component and the test above).
npm i react@18.3.1 react-dom@18.3.1 @testing-library/react@16 @testing-library/dom@10 @testing-library/user-event@14 jsdom@25 tsx typescript@5 @types/react@18 @types/react-dom@18 @types/node@22
node --import tsx wizard/wizard.test.tsx
npx tsc --noEmit
dom-env.mjs (copies the jsdom window's globals onto Node's global object):
import { JSDOM } from 'jsdom';
const { window } = new JSDOM('<!doctype html><body></body>', { url: 'http://localhost/', pretendToBeVisual: true });
for (const k of Object.getOwnPropertyNames(window)) if (!(k in globalThis)) Object.defineProperty(globalThis, k, { configurable: true, get: () => window[k] });
globalThis.IS_REACT_ACT_ENVIRONMENT = true;
package.json:
{ "type": "module" }
tsconfig.json:
{"compilerOptions":{"jsx":"react-jsx","strict":true,"module":"esnext","moduleResolution":"bundler","target":"es2022","allowImportingTsExtensions":true,"noEmit":true,"skipLibCheck":true}}
Without "type": "module" the test does not compile (esbuild, used by tsx, reports Top-level await is currently not supported with the "cjs" output format); without "jsx": "react-jsx" the JSX becomes React.createElement calls and the run stops with ReferenceError: React is not defined.
A form must not submit when client-side validation fails. In vanilla JavaScript, show how you handle the submit event so the browser does not send the request, tell the user what is wrong, and give them somewhere accessible to land. Which event methods do you rely on and why?
Sample Answer
Direct answer
Listen for the form's submit event (not a click on the button), check validity inside the handler, and call event.preventDefault() when the form is invalid. preventDefault() cancels the event's default action, which for submit is sending the form and navigating, so the page stays where it is. Use form.checkValidity() (silent) to decide, show the problems yourself, and move focus to a focusable summary of errors with a link to each field. When the form is valid, do nothing and let the browser submit (or call preventDefault() and fetch yourself).
The handler
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>Join the waitlist</title></head>
<body>
<form id="waitlist" action="/ok" method="post" novalidate>
<div id="summary" tabindex="-1" hidden>
<h2>Please fix these fields</h2>
<ul id="summary-list"></ul>
</div>
<label for="email">Email</label>
<input id="email" name="email" type="email" required>
<label for="age">Age (18 or over)</label>
<input id="age" name="age" type="number" min="18" max="120" required>
<button type="submit">Join</button>
</form>
<script>
const form = document.getElementById('waitlist');
const summary = document.getElementById('summary');
const list = document.getElementById('summary-list');
function describe(input) {
const v = input.validity;
if (input.name === 'email') return v.valueMissing ? 'Enter your email address' : 'Enter an email address like name@example.com';
if (v.valueMissing) return 'Enter your age';
return 'Age must be a number from 18 to 120';
}
form.addEventListener('submit', (event) => {
if (form.checkValidity()) return; // valid: do nothing, the browser submits normally
event.preventDefault(); // invalid: cancel the submission, the page stays put
list.replaceChildren();
for (const input of form.querySelectorAll(':invalid')) {
const li = document.createElement('li');
const a = document.createElement('a');
a.href = `#${input.id}`;
a.textContent = describe(input);
a.addEventListener('click', (e) => { e.preventDefault(); input.focus(); });
li.append(a);
list.append(li);
}
summary.hidden = false;
summary.focus(); // somewhere accessible to land: a focusable summary with links to each field
});
</script>
</body>
</html>
Which event methods and why
Start with the first three rows: submit, preventDefault() and checkValidity() are the working core, and the later rows cover the alternatives an interviewer may ask about.
| Method / event | Used for | Why this and not the alternative |
|---|---|---|
submit event on the <form> | The single place every submission passes through | Clicking the button, pressing Enter in a field, and form.requestSubmit() all fire it. A click listener on the button misses requestSubmit() and treats the click as the whole story. |
event.preventDefault() | Cancel the default action (the request and the navigation) | MDN: it tells the browser the event is being handled, so the default action should not occur. The submit event is cancelable. |
form.checkValidity() | Ask "is every control valid?" without showing any browser UI | It returns a boolean and fires an invalid event on each failing control. reportValidity() would also pop the browser's own bubble on the first one, which fights a custom summary. |
element.focus() | Move the keyboard cursor to the summary (tabindex="-1" makes a non-interactive element focusable by script) | Without it a keyboard or screen reader user stays on the Join button with no sign anything happened. |
form.requestSubmit() | Submit from script the way a button would | It fires submit (and, unless the form has novalidate, runs the browser's own validation first, per MDN); form.submit() does neither (it just sends), so a handler would never see it. |
Vocabulary for the next lines. An event "bubbles" when, after firing on its target element, it also fires on each ancestor in turn up to the document; "propagation" is that travel. Before bubbling there is a capture phase in which the event travels from the document down to the target; a listener added normally runs in the bubble phase, and passing true as the third argument to addEventListener makes it run in the capture phase instead. "Cancelable" means the event has a default action that preventDefault() is allowed to cancel, and event.defaultPrevented becomes true once it has. :invalid is a CSS pseudo-class (a selector for an element state) matching form controls that currently fail their constraints, which is how the handler's querySelectorAll(':invalid') finds the failing fields.
Not needed: stopPropagation(). It stops the event reaching other listeners (analytics, a framework) on the elements it has yet to visit, and is independent of preventDefault(), which does not stop propagation either. return false also does not work here: in a listener added with addEventListener the return value is ignored (the run below confirms the form is still sent); it cancels only from an onsubmit attribute or property handler, which the check also exercises. The invalid event does not bubble, so if you listen for it on the form you need the capture phase (addEventListener('invalid', fn, true)).
Accessible landing place
The summary has tabindex="-1", a heading and one link per problem. After a failed submit summary.focus() puts the keyboard cursor there; each link calls input.focus() for its field. The summary is rebuilt on every attempt, listing only fields that are still invalid, so fixing one and submitting again shortens the list. novalidate on the form switches off the browser's own bubbles so there is one source of messages. The server must still validate; none of this stops a hand-made request.
Proof
The check loads the page in Chromium, Firefox and WebKit through Playwright 1.48.2 (WebKit here is not Safari on iOS), with the server faked by request routing so form posts are visible:
import { chromium, firefox, webkit } from 'playwright';
import { readFileSync } from 'node:fs';
import assert from 'node:assert/strict';
const html = readFileSync(new URL('./form.html', import.meta.url), 'utf8');
const results = [];
for (const [name, type] of [['chromium', chromium], ['firefox', firefox], ['webkit', webkit]]) {
const browser = await type.launch();
const page = await browser.newPage();
const posts = [];
await page.route('http://app.test/**', (route) => {
const req = route.request();
if (req.url().endsWith('/ok')) { posts.push(req.method() + ' ' + req.postData()); return route.fulfill({ contentType: 'text/html', body: '<p id="sent">sent</p>' }); }
return route.fulfill({ contentType: 'text/html', body: html });
});
await page.goto('http://app.test/form');
await page.evaluate(() => {
window.log = { submit: 0, prevented: [], invalid: 0 };
const f = document.getElementById('waitlist');
f.addEventListener('submit', (e) => setTimeout(() => window.log.prevented.push(e.defaultPrevented), 0)); // after the page handler ran
f.addEventListener('invalid', () => window.log.invalid++, true); // 'invalid' does not bubble: capture it
});
// 1. Empty submit by clicking
await page.click('button');
await page.waitForFunction(() => window.log.prevented.length === 1); // the listener records inside a setTimeout: wait for it instead of racing it
const a = await page.evaluate(() => ({ url: location.href, active: document.activeElement.id, hidden: document.getElementById('summary').hidden, items: [...document.querySelectorAll('#summary-list a')].map((x) => x.textContent), log: window.log }));
assert.equal(a.url, 'http://app.test/form'); assert.equal(a.active, 'summary'); assert.equal(a.hidden, false);
assert.deepEqual(a.items, ['Enter your email address', 'Enter your age']);
assert.equal(posts.length, 0);
assert.deepEqual(a.log.prevented, [true]); // the submit event's default (sending the form) was cancelled
// 2. Enter inside a field goes through the same submit event
await page.click('#email'); await page.keyboard.type('ada@example.com'); await page.keyboard.press('Enter');
const b = await page.evaluate(() => ({ items: [...document.querySelectorAll('#summary-list a')].map((x) => x.textContent), active: document.activeElement.id }));
assert.deepEqual(b.items, ['Enter your age']); assert.equal(b.active, 'summary'); assert.equal(posts.length, 0);
// 3. A summary link moves focus to the field
await page.click('#summary-list a');
assert.equal(await page.evaluate(() => document.activeElement.id), 'age');
// 4. requestSubmit() fires the submit event like a button click would (this form has novalidate, so the page's own handler does the checking)
await page.evaluate(() => document.getElementById('waitlist').requestSubmit());
await page.waitForFunction(() => window.log.prevented.length === 3);
assert.deepEqual(await page.evaluate(() => window.log.prevented), [true, true, true]);
assert.equal(posts.length, 0);
// 5. Valid submit is not cancelled and the browser sends the request
await page.fill('#age', '34');
await Promise.all([page.waitForNavigation(), page.click('button')]);
assert.equal(posts.length, 1);
assert.match(posts[0], /^POST email=ada%40example.com&age=34$/);
// 6. The wrong tool: returning false from an addEventListener handler does NOT cancel the submission
await page.goto('http://app.test/form');
await page.evaluate(() => document.getElementById('waitlist').addEventListener('submit', () => false));
await page.fill('#email', 'x@y.com'); await page.fill('#age', '40');
await Promise.all([page.waitForNavigation(), page.click('button')]);
assert.equal(posts.length, 2);
// 6b. ...but returning false from an onsubmit property handler does cancel it
await page.goto('http://app.test/form');
await page.evaluate(() => { document.getElementById('waitlist').onsubmit = () => false; });
await page.fill('#email', 'x@y.com'); await page.fill('#age', '40');
await page.click('button'); await page.waitForTimeout(100);
assert.equal(posts.length, 2);
assert.equal(page.url(), 'http://app.test/form');
// 7. invalid events: one per failing control, none bubbling to the form
await page.goto('http://app.test/form');
await page.evaluate(() => { window.n = 0; document.getElementById('waitlist').addEventListener('invalid', () => window.n++); window.nCapture = 0; document.getElementById('waitlist').addEventListener('invalid', () => window.nCapture++, true); });
await page.click('button');
const inv = await page.evaluate(() => ({ bubbling: window.n, capture: window.nCapture }));
assert.deepEqual(inv, { bubbling: 0, capture: 2 });
results.push(`${name}: ok summaryItems=${a.items.length} invalidEventsCaptured=${inv.capture} invalidEventsBubbling=${inv.bubbling}`);
await browser.close();
}
console.log(results.join('\n'));
console.log('ALL CHECKS PASSED in chromium, firefox, webkit');
Run as described under Running the code, it prints the three browser lines and ALL CHECKS PASSED in chromium, firefox, webkit:
chromium: ok summaryItems=2 invalidEventsCaptured=2 invalidEventsBubbling=0
firefox: ok summaryItems=2 invalidEventsCaptured=2 invalidEventsBubbling=0
webkit: ok summaryItems=2 invalidEventsCaptured=2 invalidEventsBubbling=0
ALL CHECKS PASSED in chromium, firefox, webkit
It asserts that an empty submit leaves the URL unchanged, sends no request, records defaultPrevented as true on the submit event, lists two problems and focuses the summary; that Enter inside a field does the same with the one remaining problem; that requestSubmit() fires the same event; that a valid form is sent as a POST with email=ada%40example.com&age=34; that a listener returning false does not stop the request while an onsubmit property returning false does. Deleting the preventDefault() line makes it fail because the page navigates away.
Reading the harness: page.route intercepts every request to the fake host app.test, serving the form HTML for the page and answering /ok itself while recording the method and body in posts, so "was the form sent?" becomes "is posts empty?". The submit listener added from the test runs after the page's own handler, because it was registered later; wrapping its read of e.defaultPrevented in setTimeout(..., 0) also delays it until all handlers have finished, so the recorded value is the final one. That timeout is also why the test waits with page.waitForFunction for the record to appear before reading it: reading straight after the click can run before the timer fires, which makes the check fail on an occasional run. waitForNavigation waits for the page to load a new document, which only happens when the submit was not cancelled.
Edge cases and pitfalls
- A
<button>inside a form istype="submit"by default;type="button"does not firesubmit, so use it for buttons that are not the form's action. - Calling
preventDefault()always, then forgetting to send: the form silently does nothing. - A handler that throws before it reaches
preventDefault()lets the invalid form go through; put the guard first. - Double submission when valid: disable or guard the in-flight request before calling
fetch.
Running the code
Save the HTML block as form.html and the JavaScript block as check.mjs in one folder, then run, in the mcr.microsoft.com/playwright:v1.48.2-jammy container from that folder:
npm i playwright@1.48.2
node check.mjs
The output is the block shown under Proof, identical on ten consecutive runs.
Unlock Full Question Bank
Get access to all 12 UI Component Implementation: Forms and States interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.