Frontend development · Intermediate · 25 min
Validate a form in JavaScript with the Constraint Validation API
By Padding · Updated 18 Nov 2026
Modern browsers · HTML Living Standard constraint validation · Node.js 26.13.1 LTS · checked in Chromium with Playwright 1.65.1
You will turn an HTML sign-up form into one that writes its own error messages with the Constraint Validation API, checks fields as people leave them, sends with fetch and gives the same accessible errors from the server when JavaScript is off.
On this page
Browsers check forms for you. Add required, type="email" or pattern to an input and the browser refuses to submit until the value fits, then shows a small bubble. The bubble is the weak part: you cannot style it, its wording comes from the browser rather than your product, it disappears after a few seconds, and it only ever shows one problem at a time.
The Constraint Validation API lets you keep the browser's checking and replace only the reporting. Each field already knows whether it is valid and which rule it broke. You read that, write your own message next to the field, and mark the field so assistive technology announces the problem. You add one rule the browser has no attribute for (the two passwords must match) and send the form with fetch.
You will build a sign-up form served by a small Node.js server with no dependencies. The server matters for two reasons. Anything the browser checks can be bypassed, so the server checks everything again. And when JavaScript does not load, which happens on slow or interrupted mobile connections, the server returns the same messages in the same places, so nobody gets a worse form. The design side of these errors (when to show them and how to word them) is covered in design form errors and inline validation; this tutorial builds it.
Step 1 · Write the form and its server
Make a demo folder. The messages live in one small module, rules.js, that both the server and the browser import, so the wording can never drift apart.
mkdir -p ~/signup-form-demo
cd ~/signup-form-demo
cat > package.json <<'JSON'
{ "name": "signup-form-demo", "private": true, "type": "module" }
JSON
cat > rules.js <<'JS'
// Shared by the server and the browser, so both say the same thing.
export const USERNAME_PATTERN = '[a-z0-9_]{3,20}';
export const messages = {
name: { valueMissing: 'Enter your full name.' },
email: {
valueMissing: 'Enter your email address.',
typeMismatch: 'Enter an email address like amara@example.com.',
},
username: {
valueMissing: 'Choose a username.',
patternMismatch: 'Use 3 to 20 lower-case letters, numbers or underscores.',
taken: 'That username is taken. Try another.',
},
password: {
valueMissing: 'Enter a password.',
tooShort: 'Use at least 12 characters.',
},
confirm: {
valueMissing: 'Enter your password again.',
mismatch: 'The passwords do not match.',
},
};
JSNow the server. It renders the form, serves three static files, and handles POST /signup. A request that asks for JSON (the fetch you add later) gets JSON back. A plain form post gets the page again with the errors written in, or a redirect to a welcome page.
cd ~/signup-form-demo
cat > server.js <<'JS'
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { messages, USERNAME_PATTERN } from './rules.js';
const PORT = Number(process.env.PORT ?? 8040);
const TAKEN = new Set(['admin', 'amara']); // stands in for a database lookup
// The HTML standard's own definition of a valid email address.
const EMAIL = /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
// Browsers anchor pattern and compile it with the v flag; do the same.
const USERNAME = new RegExp(`^(?:${USERNAME_PATTERN})$`, 'v');
const STATIC = { '/style.css': 'text/css', '/signup.js': 'text/javascript', '/rules.js': 'text/javascript' };
const FIELDS = [
{ name: 'name', label: 'Full name', type: 'text', attrs: 'required autocomplete="name"' },
{ name: 'email', label: 'Email address', type: 'email', attrs: 'required autocomplete="email" spellcheck="false"' },
{ name: 'username', label: 'Username', type: 'text', hint: '3 to 20 lower-case letters, numbers or underscores.',
attrs: `required pattern="${USERNAME_PATTERN}" autocomplete="username" autocapitalize="none" spellcheck="false"` },
{ name: 'password', label: 'Password', type: 'password', hint: 'At least 12 characters.',
attrs: 'required minlength="12" autocomplete="new-password"' },
{ name: 'confirm', label: 'Confirm password', type: 'password', attrs: 'required autocomplete="new-password"' },
];
const esc = (s) => String(s).replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
function renderField(f, values, errors, isFirstError) {
const error = errors[f.name] ?? '';
const describedBy = [f.hint && `${f.name}-hint`, `${f.name}-error`].filter(Boolean).join(' ');
const value = f.type === 'password' ? '' : esc(values[f.name] ?? '');
return `<div class="field">
<label for="${f.name}">${f.label}</label>
${f.hint ? `<p class="hint" id="${f.name}-hint">${f.hint}</p>` : ''}
<input id="${f.name}" name="${f.name}" type="${f.type}" value="${value}" ${f.attrs} aria-describedby="${describedBy}"${error ? ' aria-invalid="true"' : ''}${isFirstError ? ' autofocus' : ''}>
<p class="error" id="${f.name}-error">${esc(error)}</p>
</div>`;
}
function page(values = {}, errors = {}) {
const first = FIELDS.find((f) => errors[f.name])?.name;
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Create an account</title>
<link rel="stylesheet" href="/style.css">
<script type="module" src="/signup.js"></script>
</head>
<body>
<main>
<h1>Create an account</h1>
<form id="signup" method="post" action="/signup" novalidate>
${FIELDS.map((f) => renderField(f, values, errors, f.name === first)).join('\n ')}
<button type="submit">Create account</button>
<p id="status" role="status"></p>
</form>
</main>
</body>
</html>`;
}
const welcome = () => `<!doctype html><html lang="en"><head><meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1"><title>Welcome</title>
<link rel="stylesheet" href="/style.css"></head><body><main><h1>Account created</h1></main></body></html>`;
function validate(v) {
const m = messages;
const errors = {};
if (!v.name) errors.name = m.name.valueMissing;
if (!v.email) errors.email = m.email.valueMissing;
else if (!EMAIL.test(v.email)) errors.email = m.email.typeMismatch;
if (!v.username) errors.username = m.username.valueMissing;
else if (!USERNAME.test(v.username)) errors.username = m.username.patternMismatch;
else if (TAKEN.has(v.username)) errors.username = m.username.taken;
if (!v.password) errors.password = m.password.valueMissing;
else if (v.password.length < 12) errors.password = m.password.tooShort;
if (!v.confirm) errors.confirm = m.confirm.valueMissing;
else if (v.confirm !== v.password) errors.confirm = m.confirm.mismatch;
return errors;
}
async function readForm(req) {
const chunks = [];
let size = 0;
for await (const chunk of req) {
size += chunk.length;
if (size > 10_000) throw new Error('Body too large');
chunks.push(chunk);
}
// Request.formData() understands both urlencoded and multipart bodies.
const request = new Request('http://localhost/', {
method: 'POST',
headers: { 'content-type': req.headers['content-type'] ?? '' },
body: Buffer.concat(chunks),
});
return request.formData();
}
function send(res, status, type, body) {
res.writeHead(status, { 'content-type': `${type}; charset=utf-8` });
res.end(body);
}
createServer(async (req, res) => {
const { pathname } = new URL(req.url, 'http://localhost');
try {
if (req.method === 'GET' && pathname === '/') return send(res, 200, 'text/html', page());
if (req.method === 'GET' && pathname === '/welcome') return send(res, 200, 'text/html', welcome());
if (req.method === 'GET' && STATIC[pathname]) {
return send(res, 200, STATIC[pathname], await readFile(new URL(`.${pathname}`, import.meta.url)));
}
if (req.method === 'POST' && pathname === '/signup') {
const form = await readForm(req);
const values = Object.fromEntries(FIELDS.map((f) => [f.name, String(form.get(f.name) ?? '')]));
values.email = values.email.trim(); // browsers trim email values too
const errors = validate(values);
const ok = Object.keys(errors).length === 0;
// if (ok) save the account here, hashing the password first
if (req.headers.accept?.includes('application/json')) {
return send(res, ok ? 200 : 422, 'application/json', JSON.stringify(ok ? { ok } : { ok, errors }));
}
if (ok) {
res.writeHead(303, { location: '/welcome' });
return res.end();
}
return send(res, 422, 'text/html', page(values, errors));
}
send(res, 404, 'text/plain', 'Not found');
} catch {
send(res, 400, 'text/plain', 'Bad request');
}
}).listen(PORT, '127.0.0.1', () => console.log(`Sign-up form on http://127.0.0.1:${PORT}`));
JSA few choices in that file are worth a second look:
novalidateis in the HTML. It switches off the browser's bubbles on submit but leaves every rule active, so the API in the next steps still reports on them. Because it is in the markup rather than added by script, a visitor without JavaScript sends the form straight to the server and gets the server's messages, which are the ones your script will show.- Each input points at its error with
aria-describedby, even while the error paragraph is empty. An empty paragraph adds nothing to what a screen reader reads; a filled one is read after the label and hint. - The server re-checks every rule, including the email format (with the regular expression the HTML standard defines for
type="email") and the pattern (anchored, with thevflag, as browsers compile it). Passwords are never written back into the page. - No
patternon the name field. Names such as Adébáyọ̀, Nguyễn or ሰላም do not fit a Latin-letters rule, and a name field that refuses them fails real people.
Add a stylesheet and an empty script for now:
cd ~/signup-form-demo
cat > style.css <<'CSS'
:root {
--text: #1b1f24;
--muted: #5a6270;
--line: #7d8592;
--error: #b42318;
--accent: #0f5e5a;
}
* { box-sizing: border-box; }
body { margin: 0; background: #fff; color: var(--text); font: 1rem/1.5 system-ui, sans-serif; }
main { max-width: 28rem; margin: 0 auto; padding: 1rem; }
.field { margin-bottom: 1.25rem; }
label { display: block; font-weight: 600; }
.hint { margin: 0; color: var(--muted); font-size: 0.875rem; }
input {
width: 100%;
min-height: 3rem;
margin-top: 0.25rem;
padding: 0.5rem 0.75rem;
border: 1px solid var(--line);
border-radius: 0.375rem;
font: inherit;
}
input[aria-invalid="true"] { border: 2px solid var(--error); }
input:focus-visible, button:focus-visible { outline: 3px solid var(--accent); outline-offset: 2px; }
.error { margin: 0.25rem 0 0; color: var(--error); font-weight: 600; }
.error:empty { display: none; }
button {
min-height: 3rem;
padding: 0 1.5rem;
border: 0;
border-radius: 0.375rem;
background: var(--accent);
color: #fff;
font: inherit;
font-weight: 600;
}
CSS
touch signup.jsAn invalid field gets a thicker red border and a bold message in words, so the error never depends on colour alone.
Start the server and leave it running in this terminal:
node server.jsCheck it worked
The terminal prints Sign-up form on http://127.0.0.1:8040. Open that address. You see five labelled fields and a Create account button. Type Amara in Full name and amara@ in Email address, then press Create account. No bubble appears; the page reloads at /signup with your name and email still filled in, red-bordered fields, and a message under each problem field, starting with Enter an email address like amara@example.com. The cursor is already in the email field, put there by autofocus.
You can see the same thing from a second terminal:
curl -s -X POST http://127.0.0.1:8040/signup -d 'name=Amara&email=amara@' | grep -oE 'id="[a-z]+-error">[^<]+'It prints four lines, one per field with a problem:
id="email-error">Enter an email address like amara@example.com.
id="username-error">Choose a username.
id="password-error">Enter a password.
id="confirm-error">Enter your password again.Step 2 · Ask a field what is wrong with it
Before writing the script, see what the browser knows. Reload http://127.0.0.1:8040, open the developer tools console (F12, or Cmd and Option and J on a Mac in Chrome) and type these lines one at a time:
const form = document.getElementById('signup');
const email = form.elements.email;
email.value = 'amara@';
email.checkValidity(); // false
email.validity.typeMismatch; // true
email.validity.valueMissing; // false
email.validationMessage; // the browser's own wording
form.noValidate; // true: rules still run, bubbles do notcheckValidity() answers yes or no. The validity object says why: it has one true-or-false flag per rule (valueMissing, typeMismatch, patternMismatch, tooShort, customError and a few more) and valid, which is true only when all of them are false. validationMessage is the browser's text for the first failure, written in the browser's language rather than your page's, which is one more reason to use your own messages.
Now try the password:
const password = form.elements.password;
password.value = 'short';
password.validity.tooShort; // falseIt says false, although five characters is under minlength="12". The standard only reports tooShort after a person has edited the field, never for a value set by script. Type short into the Password box on the page and run password.validity.tooShort again: now it is true. This is also why the server checks the length itself.
Check it worked
Your console showed false for email.checkValidity(), true for email.validity.typeMismatch, true for form.noValidate, and tooShort changed from false to true only after you typed into the field. Reload the page to clear the values you set.
Step 3 · Show your own messages on submit
Now write signup.js. It needs four pieces: pick the message for a field from its validity flags, write it into the field's error paragraph, enforce the password match with setCustomValidity, and check every field on submit.
cd ~/signup-form-demo
cat > signup.js <<'JS'
import { messages } from './rules.js';
const form = document.getElementById('signup');
const status = document.getElementById('status');
const fields = [...form.querySelectorAll('input')];
const { password, confirm } = form.elements;
const REASONS = ['valueMissing', 'typeMismatch', 'patternMismatch', 'tooShort'];
function messageFor(field) {
if (field.validity.customError) return field.validationMessage;
const reason = REASONS.find((r) => field.validity[r]);
return messages[field.name]?.[reason] ?? field.validationMessage;
}
function showError(field, text) {
document.getElementById(`${field.id}-error`).textContent = text;
if (text) field.setAttribute('aria-invalid', 'true');
else field.removeAttribute('aria-invalid');
}
// A rule HTML has no attribute for. A non-empty string makes the field
// invalid with validity.customError; an empty string makes it valid again.
function matchPasswords() {
const differs = confirm.value !== '' && confirm.value !== password.value;
confirm.setCustomValidity(differs ? messages.confirm.mismatch : '');
}
function check(field) {
matchPasswords();
const valid = field.checkValidity();
showError(field, valid ? '' : messageFor(field));
return valid;
}
form.addEventListener('submit', (event) => {
const invalid = fields.filter((field) => !check(field));
if (invalid.length > 0) {
event.preventDefault();
invalid[0].focus();
}
});
JSThe order of the submit listener matters. It checks every field, so all problems show at once, then moves focus to the first one. A screen reader then reads that field's label, its hint, its error and "invalid", so the person hears what to fix without hunting for it. If everything passes, the listener does nothing and the form posts to the server as before.
setCustomValidity is the API's hook for your own rules. Its message is what validationMessage returns while it is set, which is why messageFor uses it directly for customError. Forgetting to set it back to '' is the classic bug: the field then stays invalid forever. check calls matchPasswords every time, so the custom error always reflects the current values.
Check it worked
Reload the page and press Create account with every field empty. All five fields turn red with a message under each, and the cursor lands in Full name. The address bar still shows http://127.0.0.1:8040/, because nothing was sent. Fill the passwords with lagos-rain-2026 and lagos-rain-2025 and press Create account again: Confirm password reads The passwords do not match.
Step 4 · Check each field as people leave it
Waiting for submit means someone can fill in eight fields before learning that the first one was wrong. Checking on every keystroke is worse: the email field complains after the first letter. The middle ground is to check when the person leaves a field (blur), then, once a field is showing an error, re-check it on every keystroke so the message disappears the moment it is fixed.
One exception: tabbing through an empty field to look at the rest of the form is not a mistake, so an empty field that has no error yet is left alone until submit.
cd ~/signup-form-demo
cat >> signup.js <<'JS'
for (const field of fields) {
field.addEventListener('blur', () => {
if (field.value !== '' || field.hasAttribute('aria-invalid')) check(field);
});
field.addEventListener('input', () => {
if (field.hasAttribute('aria-invalid')) check(field);
});
}
// Changing the first password can fix, or break, the second.
password.addEventListener('input', () => {
if (confirm.hasAttribute('aria-invalid')) check(confirm);
});
JSBecause the browser keeps validity up to date on its own, these listeners only decide when to show the result. None of them re-implements a rule.
Check it worked
Reload. Click in Full name and press Tab without typing: no message. Type amara@ in Email address and press Tab: Enter an email address like amara@example.com. appears. Go back and add example.com: the message disappears as you type the first letter that makes the address valid, not when you leave. Type Amara in Username and press Tab: the lower-case rule appears. Type short in Password and press Tab: Use at least 12 characters.
Step 5 · Send the form with fetch
With every check passing, the form still does a full page post. Sending it with fetch keeps the page in place, so the person's focus and scroll position stay where they were, and a failed request can be reported without losing what they typed. Append a second submit listener. It runs after the first one, and only acts if the first did not cancel the submission:
cd ~/signup-form-demo
cat >> signup.js <<'JS'
let sending = false;
form.addEventListener('submit', async (event) => {
if (event.defaultPrevented || sending) return;
event.preventDefault();
sending = true;
status.textContent = 'Creating your account…';
try {
const response = await fetch(form.action, {
method: 'POST',
headers: { accept: 'application/json' },
body: new FormData(form),
});
const result = await response.json();
if (result.ok) {
form.reset();
status.textContent = 'Account created.';
return;
}
status.textContent = '';
const failed = Object.keys(result.errors).map((name) => form.elements[name]);
for (const field of failed) showError(field, result.errors[field.name]);
failed[0]?.focus();
} catch {
status.textContent = 'Could not reach the server. Check your connection and try again.';
} finally {
sending = false;
}
});
JSnew FormData(form) collects every named field, exactly as a normal submission would. Passed as the body, it is sent as multipart/form-data; the server's Request.formData() reads that as easily as the urlencoded body a plain form post sends. The accept header tells the server to answer with JSON instead of a page.
Server errors go through the same showError as browser errors, so a rule only the server can check looks identical to one the browser checks. The username amara is the example here: it fits the pattern, but it is already taken. Once shown, the error clears as the person types a new name, because the input listener re-checks the field and the browser finds nothing wrong.
The status paragraph has role="status", so screen readers announce "Creating your account…" and "Account created." without moving focus. On prepaid data or a weak signal the request can take several seconds, and that message is what tells people the button did something. Announce errors and notices with a live region covers live regions in depth.
Check it worked
Reload and fill in a name, a valid email, the username amara, and lagos-rain-2026 in both password fields. Press Create account. The page does not reload; under Username you see That username is taken. Try another. and the cursor is in that field. In the developer tools Network panel, the signup request has the type fetch and the status 422. Change the username to amara_o and press Create account again: the form empties and Account created. appears under the button.
Step 6 · Test it with and without JavaScript
A test proves the two promises of this form every time someone edits it: script users get your messages in the right places, and people without script get the same ones from the server. Leave the server running. In a second terminal, install Playwright, which drives a real browser from a script, into the demo folder. --with-deps also installs the system libraries Chromium needs on Linux and may ask for your password:
cd ~/signup-form-demo
npm install playwright@1.65.1
npx playwright install --with-deps chromiumThen write the test. The first half behaves like a keyboard and mouse user with JavaScript on. The second half opens the page with JavaScript switched off and checks that the server writes the same messages, attributes and focus target.
cd ~/signup-form-demo
cat > test-signup.mjs <<'JS'
import { chromium } from 'playwright';
import assert from 'node:assert/strict';
const url = 'http://127.0.0.1:8040/';
const browser = await chromium.launch();
// With JavaScript, on a phone-sized screen.
const page = await browser.newPage({ viewport: { width: 390, height: 844 } });
await page.goto(url);
const name = page.getByLabel('Full name');
const email = page.getByLabel('Email address');
const username = page.getByLabel('Username');
const password = page.getByLabel('Password', { exact: true });
const confirm = page.getByLabel('Confirm password');
const submit = page.getByRole('button', { name: 'Create account' });
const errorText = (p, id) => p.locator(`#${id}-error`).textContent();
// What the validity object reports for script-set values.
const facts = await page.evaluate(() => {
const form = document.getElementById('signup');
const { email, password } = form.elements;
email.value = 'amara@';
password.value = 'short';
const result = {
noValidate: form.noValidate,
formValid: form.checkValidity(),
typeMismatch: email.validity.typeMismatch,
tooShortFromScript: password.validity.tooShort,
};
email.value = '';
password.value = '';
return result;
});
assert.deepEqual(facts, { noValidate: true, formValid: false, typeMismatch: true, tooShortFromScript: false });
// Tabbing through an empty field shows nothing.
await name.focus();
await page.keyboard.press('Tab');
assert.equal(await errorText(page, 'name'), '');
// A wrong value is reported on leaving the field and cleared once fixed.
await email.fill('amara@');
await email.press('Tab');
assert.equal(await errorText(page, 'email'), 'Enter an email address like amara@example.com.');
assert.equal(await email.getAttribute('aria-invalid'), 'true');
assert.equal(await email.getAttribute('aria-describedby'), 'email-error');
await email.fill('amara@example.com');
assert.equal(await errorText(page, 'email'), '');
assert.equal(await email.getAttribute('aria-invalid'), null);
await username.fill('Amara');
await username.press('Tab');
assert.equal(await errorText(page, 'username'), 'Use 3 to 20 lower-case letters, numbers or underscores.');
await password.pressSequentially('short');
await password.press('Tab');
assert.equal(await errorText(page, 'password'), 'Use at least 12 characters.');
await password.fill('lagos-rain-2026');
await confirm.fill('lagos-rain-2025');
await confirm.press('Tab');
assert.equal(await errorText(page, 'confirm'), 'The passwords do not match.');
await confirm.fill('lagos-rain-2026');
assert.equal(await errorText(page, 'confirm'), '');
// Submit with problems: focus goes to the first one and nothing is sent.
let posts = 0;
page.on('request', (r) => { if (r.url().endsWith('/signup')) posts++; });
await submit.click();
assert.equal(await page.evaluate(() => document.activeElement.id), 'name');
assert.equal(await errorText(page, 'name'), 'Enter your full name.');
assert.equal(await page.locator('[aria-invalid="true"]').count(), 2, 'name and username');
assert.equal(posts, 0);
// The server has the last word: amara is taken.
await name.fill('Amara Okafor');
await username.fill('amara');
const [response] = await Promise.all([
page.waitForResponse((r) => r.url().endsWith('/signup')),
submit.click(),
]);
assert.equal(response.status(), 422);
assert.equal(response.request().resourceType(), 'fetch');
await page.locator('#username-error', { hasText: 'That username is taken. Try another.' }).waitFor();
assert.equal(await page.evaluate(() => document.activeElement.id), 'username');
assert.equal(page.url(), url, 'no page load');
await username.fill('amara_o');
assert.equal(await errorText(page, 'username'), '');
await submit.click();
await page.getByRole('status').filter({ hasText: 'Account created.' }).waitFor();
assert.equal(await name.inputValue(), '', 'form reset');
const overflow = await page.evaluate(() => document.documentElement.scrollWidth > document.documentElement.clientWidth);
assert.equal(overflow, false, 'no sideways scrolling on a phone');
// Without JavaScript: the server gives the same errors.
const noScript = await browser.newContext({ javaScriptEnabled: false });
const plain = await noScript.newPage();
await plain.goto(url);
await plain.getByLabel('Full name').fill('Amara Okafor');
await plain.getByLabel('Email address').fill('amara@');
await plain.getByLabel('Username').fill('Amara');
await plain.getByLabel('Password', { exact: true }).fill('short');
await Promise.all([
plain.waitForURL('**/signup'),
plain.getByRole('button', { name: 'Create account' }).click(),
]);
assert.equal(await errorText(plain, 'name'), '');
assert.equal(await errorText(plain, 'email'), 'Enter an email address like amara@example.com.');
assert.equal(await errorText(plain, 'username'), 'Use 3 to 20 lower-case letters, numbers or underscores.');
assert.equal(await errorText(plain, 'password'), 'Use at least 12 characters.');
assert.equal(await errorText(plain, 'confirm'), 'Enter your password again.');
const plainEmail = plain.getByLabel('Email address');
assert.equal(await plainEmail.getAttribute('aria-invalid'), 'true');
assert.equal(await plainEmail.getAttribute('aria-describedby'), 'email-error');
assert.notEqual(await plainEmail.getAttribute('autofocus'), null, 'first problem gets focus');
assert.equal(await plainEmail.inputValue(), 'amara@', 'typed value kept');
assert.equal(await plain.getByLabel('Password', { exact: true }).inputValue(), '', 'password not sent back');
assert.equal(await plain.getByLabel('Full name').getAttribute('aria-invalid'), null);
await plainEmail.fill('amara@example.com');
await plain.getByLabel('Username').fill('amara_o');
await plain.getByLabel('Password', { exact: true }).fill('lagos-rain-2026');
await plain.getByLabel('Confirm password').fill('lagos-rain-2026');
await Promise.all([
plain.waitForURL('**/welcome'),
plain.getByRole('button', { name: 'Create account' }).click(),
]);
assert.equal(await plain.locator('h1').textContent(), 'Account created');
await browser.close();
console.log('PASS: same errors with and without JavaScript');
JS
node test-signup.mjsThe password in the first half is typed with pressSequentially, key by key, because tooShort only appears after a real edit, as you saw in the console. The test finds fields by their label text, so a broken for attribute or a renamed label fails it.
Check it worked
The last line of output is PASS: same errors with and without JavaScript. To watch it fail for the right reason, delete novalidate from the <form> line in server.js, stop the server with Ctrl+C, start it again and rerun node test-signup.mjs: it stops with an AssertionError on noValidate. Put novalidate back and restart the server before moving on.
Step 7 · Clean up
Stop the server with Ctrl+C in its terminal, then remove the demo folder, which also removes the local Playwright install. The Chromium build Playwright downloaded stays in its shared cache; npx playwright uninstall removes it if you no longer need it.
cd ~
rm -rf ~/signup-form-demoCheck it worked
http://127.0.0.1:8040 no longer loads in your browser, and ls ~/signup-form-demo reports that there is no such file or directory.
Next steps
- Add an error summary at the top of the form, with a link to each field, in build accessible HTML forms.
- Decide when each check should run and how each message should read in design form errors and inline validation.
- Announce the sending and success messages reliably across screen readers with announce errors and notices with a live region.
Part of these paths
Related tutorials
- How to Build Accessible HTML FormsYou will build a contact form that works with keyboards and screen readers, with real labels, grouped radio buttons, hints tied to their fields, autocomplete values, and an error summary that takes focus and links to each problem, checking the result against specific WCAG 2.2 criteria.
- Design form errors and inline validationYou will have a validation timing table for every field on a booking form, a message for every way each field can go wrong, and an error-states frame in Figma showing the field errors, the error summary and where focus goes.
- Announce errors and notices with a live regionYou will build two Larkfield Clinic banners, a polite "10:30 was just taken" notice and an urgent "could not book" error, that screen readers announce once each, plus a Playwright script that checks them in the accessibility tree.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials