Sub topic 13
Testing form validation
This chapter covers how to check that your form validation works and keeps working. It assumes you have read the earlier chapters on constraint attributes, the Constraint Validation API, accessible error messages, and server-side validation. You should also know how to run a Node.js script and install a package with npm.
Why validation needs its own tests
Validation fails quietly. A typo in a pattern attribute does not throw an error. It just accepts input it should reject, or rejects input it should accept. Client and server rules also drift apart over time. If someone changes maxlength in the HTML and forgets the server, users see confusing results.
Validation has three layers, and each needs a different kind of test:
- Rules: the logic that decides whether a value is acceptable. This is the server function, and it is fast to test.
- Browser behavior: attributes,
validity,setCustomValidity, error text, focus, andaria-invalid. This needs a real browser. - Experience: keyboard use, screen reader announcements, and error wording. This needs a person.
Test the server rules first
The server is the source of truth, so start there. The validateSignup function from the previous chapter is a pure function. It takes an object and returns an object of errors, so it needs no browser or network.
Add export before function validateSignup and save it as validate.js (use "type": "module" in package.json). Then create validate.test.js:
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { validateSignup } from './validate.js';
const valid = { email: '[email protected]', username: 'ada_l', age: '36' };
test('accepts a valid submission', () => {
assert.deepEqual(validateSignup(valid), {});
});
const cases = [
['missing email', { email: undefined }, 'email'],
['email without @', { email: 'ada.example.com' }, 'email'],
['username too short (2)', { username: 'ab' }, 'username'],
['username too long (21)', { username: 'a'.repeat(21) }, 'username'],
['username with uppercase', { username: 'Ada' }, 'username'],
['age below minimum (17)', { age: '17' }, 'age'],
['age above maximum (121)', { age: '121' }, 'age'],
['age not whole', { age: '18.5' }, 'age'],
['age not a number', { age: 'abc' }, 'age'],
['age missing', { age: undefined }, 'age'],
];
for (const [name, override, field] of cases) {
test(`rejects ${name}`, () => {
const errors = validateSignup({ ...valid, ...override });
assert.ok(errors[field], `expected an error for ${field}`);
});
}
const boundaries = [
['username of 3 characters', { username: 'abc' }],
['username of 20 characters', { username: 'a'.repeat(20) }],
['age 18', { age: '18' }],
['age 120', { age: '120' }],
];
for (const [name, override] of boundaries) {
test(`accepts ${name}`, () => {
assert.deepEqual(validateSignup({ ...valid, ...override }), {});
});
}Run it with node --test.
Test the boundaries
Most validation bugs sit at the edges of a rule. For every range, test the value just inside and just outside each limit. For minlength="3", test lengths 2 and 3. For max="120", test 120 and 121. Also test the odd values users and scripts send:
- A missing field, which arrives as
undefined. - An empty string and a string of only spaces.
- Text where a number belongs.
- A value much longer than
maxlength. - Unexpected types, such as an array when two fields share a name.
Check for client and server mismatches
The sample form in this tutorial has a gap. The age input has min and max but no required, so the browser lets an empty age through. The server rejects a missing age. The user sees a server error for a rule the form never mentioned.
Cases like this need a decision, not a patch. Either add required to the HTML or make the server accept an empty age. Writing the tests above is how you find these mismatches, because each test forces you to state what the rule is.
Test browser behavior in a real browser
Attributes such as required and pattern are enforced by the browser, not by your code. A simulated DOM does not run the same error flow, so use a real browser for these tests. Playwright is a common choice. Install it with npm init playwright@latest, and set baseURL in playwright.config.js to your dev server, for example http://localhost:3000.
The test below uses the form and submit handler from earlier in this tutorial. It assumes each field has a matching <p id="email-error">-style element, such as username-error.
import { test, expect } from '@playwright/test';
test.describe('signup form', () => {
test.beforeEach(async ({ page }) => {
await page.goto('/signup');
});
test('empty submit shows errors and focuses the first invalid field', async ({ page }) => {
await page.getByRole('button', { name: 'Sign up' }).click();
const email = page.getByLabel('Email');
await expect(email).toHaveAttribute('aria-invalid', 'true');
await expect(page.locator('#email-error')).not.toBeEmpty();
await expect(email).toBeFocused();
});
test('pattern mismatch is reported on the username', async ({ page }) => {
const username = page.getByLabel('Username');
await username.fill('Bad Name!');
const state = await username.evaluate((el) => ({
patternMismatch: el.validity.patternMismatch,
valid: el.validity.valid,
}));
expect(state).toEqual({ patternMismatch: true, valid: false });
});
test('a valid form clears errors', async ({ page }) => {
await page.getByRole('button', { name: 'Sign up' }).click();
await page.getByLabel('Email').fill('[email protected]');
await page.getByLabel('Username').fill('ada_l');
await page.getByLabel('Age').fill('36');
await page.getByRole('button', { name: 'Sign up' }).click();
await expect(page.locator('#email-error')).toBeEmpty();
await expect(page.getByLabel('Email')).not.toHaveAttribute('aria-invalid');
});
test('the server rejects a request that skips the browser', async ({ request }) => {
const response = await request.post('/signup', {
form: { email: 'nope', username: 'X', age: '5' },
});
expect(response.ok()).toBe(false);
});
});The last test posts directly to the server and never loads the page. It proves the server does not depend on the browser's checks. Adjust the final assertion to your app's real status code, such as 400 or 422.
What to assert and what to avoid
Query controls by label with getByLabel. This confirms the label is wired to the input, which is an accessibility check as well as a convenience. Assert on validity flags and on the presence of error text. Avoid asserting exact built-in messages such as "Please fill out this field." Each browser words these differently and translates them to the user's language. A test that matches the exact string breaks when you switch browsers.
Custom messages that you set with setCustomValidity are your own text, so you can assert those exactly.
Test custom and cross-field rules
Custom rules are where hand-written logic enters the browser, so they need the most attention. For the password confirmation example, test these sequences:
- Type a password and a different confirmation. The confirmation must be invalid with the message "Passwords do not match."
- Change the first password field to match. Check whether the confirmation becomes valid.
The second case catches a common bug. The checkMatch function from the earlier chapter is attached to both fields, so editing either one clears the error. If you attach it only to the confirmation field, the error stays after the user fixes the password. A test that edits the other field catches that.
Also test the empty-string reset. After a failed check, setCustomValidity('') must clear the error. A field left with a stale custom message can never become valid, and the form cannot submit.
Test asynchronous checks
For checks such as username availability, control the network in the test. Playwright can intercept the request:
import { test, expect } from '@playwright/test';
test('taken username is reported', async ({ page }) => {
await page.route('**/api/username*', (route) =>
route.fulfill({ json: { available: false } })
);
await page.goto('/signup');
await page.getByLabel('Username').fill('ada_l');
await page.getByLabel('Username').blur();
await expect(page.locator('#username-error')).toContainText(/taken/i);
});Add tests for a slow response, a failed request, and two responses arriving out of order. The last one catches the case where an old answer overwrites the result for newer input.
Test with the keyboard and a screen reader
Automated tests cannot judge whether the experience works. Do these checks by hand when you change a form:
- Complete and submit the form using only the Tab, Shift+Tab, Space, and Enter keys.
- Submit with errors. Focus must move to the first invalid control, and its error must be read aloud along with its label.
- Fix one error and confirm that its message disappears and
aria-invalidis removed. - Zoom to 200% and confirm that error text is still visible and not clipped.
- Check that errors do not rely on color alone. The red border from
:user-invalidneeds accompanying text.
Try at least one screen reader, such as NVDA on Windows or VoiceOver on macOS.
A checklist before release
| Check | Layer | Tool |
|---|---|---|
| Each rule accepts and rejects at its boundaries | Server | `node --test` |
| Client and server rules agree | Server and browser | Unit and Playwright tests |
| Failed submit shows errors, sets `aria-invalid`, focuses the first field | Browser | Playwright |
| Custom messages clear when fixed | Browser | Playwright |
| Direct requests that skip the page are rejected | Server | Playwright `request` |
| Errors are announced and usable by keyboard | Experience | Manual |
Exercise
A test asserts that the required email field's error text equals "Please fill out this field." It passes in Chromium and fails in Firefox. What is the cause, and how should you change the test?
Show answer
The built-in messages come from the browser and differ between engines and languages, so an exact string match is brittle. Assert that the error element is not empty, or check field.validity.valueMissing is true. Use exact string matches only for messages you set yourself with setCustomValidity.
Exercise
You add minlength="3" to a username input and write server tests for lengths 3 and 20. A user reports that a 2-character username was accepted. Which test cases were missing, and which layer should have caught it?
Show answer
The tests lacked the cases just outside each limit, a length of 2 and a length of 21. The server rule is the source of truth, so its unit tests should have caught it. A browser test that fills "ab" and checks validity.tooShort would also help. Note that tooShort is only set after the user edits the value, so fill the field by typing rather than by script if you test it that way.