Sub topic 13
Testing Form Validation
This chapter assumes you know the built-in constraint attributes, the Constraint Validation API (validity, checkValidity, setCustomValidity), and the accessible error pattern from earlier chapters. It also assumes you have written server-side validation like validateSignup. Here you will test all three layers: the browser rules, your error-display script, and the server.
What to Test
Validation has three layers. Each fails in its own way, so each needs its own kind of test.
| Layer | What can break | How to test |
|---|---|---|
| Browser constraints | A wrong `pattern`, a missing `required`, a bad `min` | Check `validity` flags in a browser test |
| Your script | Messages not shown, `aria-invalid` not set, focus not moved | Simulate a submit and inspect the DOM |
| Server | A rule missing or looser than the client | Call the function or endpoint directly |
Start with the Server Rules
The server function is plain JavaScript with no browser dependency, so it is the cheapest to test. This example uses Node's built-in test runner. Save validateSignup from the earlier chapter in validate.js and export it with module.exports = { validateSignup };.
const test = require('node:test');
const assert = require('node:assert/strict');
const { validateSignup } = require('./validate.js');
test('accepts a valid signup', () => {
const errors = validateSignup({ email: '[email protected]', username: 'ada_1', age: '30' });
assert.deepEqual(errors, {});
});
test('rejects boundary values', () => {
assert.equal(validateSignup({ email: 'a@b', username: 'ab', age: '30' }).username !== undefined, true);
assert.equal(validateSignup({ email: 'a@b', username: 'abc', age: '17' }).age !== undefined, true);
assert.equal(validateSignup({ email: 'a@b', username: 'abc', age: '18' }).age, undefined);
});
test('rejects input a browser would have blocked', () => {
const errors = validateSignup({});
assert.ok(errors.email && errors.username && errors.age);
});
test('rejects a non-integer age', () => {
assert.ok(validateSignup({ email: 'a@b', username: 'abc', age: '20.5' }).age);
});Run it with node --test. Three habits make these tests useful:
- Test each boundary on both sides: 2 and 3 characters, 17 and 18 for age.
- Send input a browser would never send, such as an empty object or a string where a number belongs.
- Assert on the field that has the error, not on the exact message text, so wording changes do not break tests.
Test Browser Constraints in a Real Browser
Built-in validation runs in the browser engine, so test it there. The validity property tells you which rule failed without reading any message text. Here is a Playwright test, which runs in Chromium, Firefox, and WebKit.
const { test, expect } = require('@playwright/test');
test('username rejects uppercase and short values', async ({ page }) => {
await page.goto('http://localhost:3000/signup');
const username = page.locator('#username');
await username.fill('AB');
expect(await username.evaluate((el) => el.validity.tooShort)).toBe(true);
expect(await username.evaluate((el) => el.validity.patternMismatch)).toBe(true);
await username.fill('ada_1');
expect(await username.evaluate((el) => el.validity.valid)).toBe(true);
});
test('submit shows errors and focuses the first invalid field', async ({ page }) => {
await page.goto('http://localhost:3000/signup');
await page.getByRole('button', { name: 'Sign up' }).click();
await expect(page.locator('#email-error')).not.toBeEmpty();
await expect(page.locator('#email')).toHaveAttribute('aria-invalid', 'true');
await expect(page.locator('#email')).toBeFocused();
});Note that tooShort is only set after a user edit. A value set by script, or an initial value attribute, does not trigger it. Playwright's fill simulates typing, so it behaves like a user.
Test the Whole Path
Finally, send data straight to the endpoint without a browser. This proves the server does not depend on client checks.
curl -i -X POST http://localhost:3000/signup \
-d "email=not-an-email" -d "username=AB" -d "age=5"Check that the response status signals failure (commonly 400 or 422), that the body names every invalid field, and that nothing was saved. A server that returns success here has a security hole, not just a usability problem.
Manual Checks Still Matter
Automation cannot judge whether an error is understandable. Before release, walk through these by hand:
- Use only the keyboard: submit an empty form, and confirm focus lands on the first invalid field.
- Turn on a screen reader and confirm each error is announced with its field.
- Disable JavaScript and confirm the browser's default validation still works.
- Zoom to 200% and confirm error text is not clipped.
Common Mistakes
- Testing only valid input. Most bugs are in the rejection paths.
- Checking only the client. A passing browser test says nothing about the server.
- Setting a custom validity message and never clearing it. Test that fixing the value makes
validity.validtrue again.
Exercise
Your confirm field uses setCustomValidity('Passwords do not match.'). Describe two automated tests that would catch a bug where the error is never cleared after the user corrects the value.
Show answer
First, in a browser test, fill password with "abc123" and confirm with "zzz", then assert confirm.validity.customError is true. Second, fill confirm with "abc123" and assert confirm.validity.valid is true and customError is false. A third useful variant changes password after confirm is filled, to check that both fields trigger the re-check.
Exercise
Why should a server test send an empty object to validateSignup?
Show answer
A client can bypass browser validation, so the server may receive missing fields. The test confirms that missing values produce errors instead of exceptions or accepted data.