Form Validation Patterns That Don't Annoy Users
When to validate, what to say, and how to wire errors for screen readers — blur-based checks, reward-early-punish-late, and accessible error states.
By Velloreth
Form validation has an unusual failure mode: done badly, it is worse than doing nothing. A field that screams “invalid email” while the user is still typing their email does not guide anyone — it interrupts them. Baymard’s large-scale e-commerce research has found that nearly a third of sites still skip inline validation entirely; the sites that add it often make the opposite mistake, validating at exactly the wrong moment.
The goal is narrow: catch mistakes early enough that fixing them is cheap, and late enough that the user was not nagged for being mid-thought. Everything below serves that.
When to validate
There are three moments, and each has a place:
| Timing | What it feels like | Good for | Risk |
|---|---|---|---|
| On keystroke | Immediate, often premature | Password rules, character counters, availability checks | Flags incomplete input; feels punitive |
| On blur | “Done with this field” | Email, name, phone, ZIP, most text fields | Slightly delayed feedback |
| On submit | The catch-all | Server-side rules, required-field sweep | Wall of errors at the end |
Usability research — including Nielsen Norman Group’s guidance — consistently lands on blur as the default: it lines up with a natural completion signal (the user moved on), and it avoids error flashes while typing. Studies comparing blur-based validation with keystroke-based validation have found users completing forms faster with blur, because they are not constantly context-switching to error messages.
The combined pattern that works:
- First entry: validate on blur.
- While correcting an error: re-validate on input, so feedback disappears the moment the fix lands.
- Always validate again on submit, including against server responses.
That last rule is the “reward early, punish late” pattern: the first mistake gets the benefit of the doubt until the user leaves the field, and every subsequent keystroke gets immediate confirmation that it is fixed.
input.addEventListener('blur', () => validate(input));
input.addEventListener('input', () => {
if (input.getAttribute('aria-invalid') === 'true') {
validate(input); // already flagged — now respond instantly
}
});
Start with HTML, then take control
Native validation attributes are free accessibility:
<input
id="email"
name="email"
type="email"
required
autocomplete="email"
aria-describedby="email-hint"
/>
type="email" gives the browser a format check, required covers emptiness, and autocomplete lets browsers and password managers fill the field correctly — which reduces the error rate before validation even runs.
The catch: each browser has its own error bubbles, and their copy, position, and timing are not yours to control. For consistent messaging, take over:
<form novalidate>
…
</form>
novalidate disables the built-in UI while keeping the attributes — the semantics and autocomplete still work, you just drive the feedback. Then validate with the Constraint Validation API rather than writing your own regex zoo:
function validate(input) {
if (input.validity.valueMissing) return 'This field is required.';
if (input.validity.typeMismatch && input.type === 'email') {
return 'Enter an email address like name@example.com.';
}
if (input.validity.tooShort) {
return `Use at least ${input.minLength} characters.`;
}
return '';
}
Custom rules that HTML cannot express (a username policy, a server-side uniqueness check) go through setCustomValidity('message') with the customError validity state, so they slot into the same code path.
One caveat on type="email": it accepts a looser format than your server will (no TLD check, for example). That is fine — validate strictly on the server, and let the browser catch the cheap mistakes.
Wiring errors for screen readers
This is where most implementations quietly fail. A red border and a message three pixels below the input is invisible to a screen reader user unless you connect them:
<label for="email">Email address</label>
<input
id="email"
name="email"
type="email"
aria-invalid="true"
aria-describedby="email-error"
/>
<p id="email-error" class="error">Enter an email address like name@example.com.</p>
Three attributes, standard behavior:
aria-invalid="true"announces the field as invalid when focused. Remove the attribute when valid — do not set it to"false".aria-describedbylinks the message so it is read with the field. Keep helper text in the description too:aria-describedby="email-hint email-error".- When the message updates live (your on-input re-check), the containing element needs
aria-live="polite"so the change is announced without interrupting.
Two more rules:
- Never rely on color alone. A red border is one signal; pair it with an icon and the text message. Colorblind users and low-vision users with forced-colors modes both lose the border.
- Keep the message visible. Tooltips and hover-only errors do not exist for touch users or anyone navigating by keyboard.
On submit: summary, focus, and honesty
When the user hits submit with errors present, three things should happen:
- Validate every field — not only the untouched ones.
- Move focus to the first invalid field. Without this, keyboard and screen reader users land at the top of the page with no indication anything went wrong.
- For long forms, add an error summary at the top with links to each field — as a supplement to inline errors, never as their replacement.
form.addEventListener('submit', (event) => {
event.preventDefault();
const fields = [...form.querySelectorAll('input, textarea, select')];
let firstInvalid = null;
for (const field of fields) {
if (validateField(field)) continue; // valid — keep looking
if (!firstInvalid) firstInvalid = field;
}
if (firstInvalid) {
firstInvalid.focus();
return;
}
form.submit();
});
And when the server rejects the submission, preserve everything the user typed. A validation failure that clears the form is the single fastest way to lose a completion.
Writing the actual message
The message is the product. “Invalid input” describes the system’s opinion; it does not help the user.
| Instead of | Write |
|---|---|
| Invalid email | Enter an email address like name@example.com |
| Invalid phone number | Enter a phone number with 10 digits, like 9800000000 |
| Password too weak | Use at least 12 characters — a phrase works well |
| Required | Enter your full name |
| Invalid date | Enter the date as YYYY-MM-DD |
The pattern: state what is wrong in terms of what is right, and show an example when a format matters. Also keep the tone neutral — the field is wrong, the user is not.
Error placement matters as much as wording: directly below the field, in the flow of the form, adjacent to the thing it describes. Detached error lists (or worse, alert() dialogs) force the user to search.
For fields where live feedback genuinely helps, invert the message:
<ul id="pw-rules" aria-live="polite">
<li data-rule="length">At least 12 characters</li>
<li data-rule="case">Upper and lowercase letters</li>
<li data-rule="number">At least one number</li>
</ul>
A checklist that fills in as you type is guidance. The same rules shouted as failures while you type are noise.
Fields that need special handling
Most fields follow the blur-and-message pattern unchanged. A few have their own rules:
Password confirmation. Do not validate the confirmation field until both fields have content — flagging an empty “confirm password” box while the user is still on “password” is the classic premature error. Once both are filled, re-check on every input in either field.
function validateConfirmation(password, confirm) {
if (!password.value || !confirm.value) return ''; // not ready yet
return password.value === confirm.value ? '' : 'Passwords do not match.';
}
Phone and name fields. Accept formats loosely — spaces, dashes, parentheses — and normalize on the server. If your backend needs digits only, strip the punctuation yourself. Telling a user their phone number is invalid because of a hyphen is a bug wearing a validation costume.
Dates. Native <input type="date"> gives you a picker and locale-aware formatting for free; pair it with min/max for range rules instead of parsing text. If you must use a text input, state the expected format in the label, not only in the error.
File uploads. Validate type and size on the client for feedback, but treat both as advisory — users rename files, and clients lie. Show a preview immediately, and make the error message name the actual constraint: “Maximum 5 MB, PDF only.”
Email plus-addressing and unicode. user+tag@example.com is valid. So are addresses in IDN domains. Rejecting them is a common regex self-own; lean on type="email" and your server’s mail library rather than a hand-rolled pattern.
The theme across all five: be liberal in what you accept, strict in what the server does with it, and never invent a format constraint the backend does not actually have.
Async validation without the chaos
Server-side uniqueness checks (“this username is taken”) have three rules:
- Debounce. Fire after the user pauses (~300–500ms), not per keystroke.
- Show a pending state, not an error. A field that says nothing while checking is fine; a field that says “invalid” while checking is wrong.
- Handle races. If the user types
aliceand thenalice2, the first response may arrive last. Abort stale requests (AbortController) or ignore responses that no longer match the current value.
let controller = null;
input.addEventListener('input', async () => {
controller?.abort();
controller = new AbortController();
setStatus('checking');
const res = await fetch(`/api/check-username?u=${encodeURIComponent(input.value)}`, {
signal: controller.signal,
});
const { available } = await res.json();
setStatus(available ? 'available' : 'taken');
});
Re-check on submit regardless — a debounce timer is not a guarantee, and the user can paste and submit in one motion.
A minimal, complete pattern
Pulling it together — blur validation, instant re-check while correcting, submit sweep, focus management:
function validateField(input) {
const error = document.getElementById(`${input.id}-error`);
let message = '';
if (input.validity.valueMissing) message = 'This field is required.';
else if (input.validity.typeMismatch) message = 'Check the format — e.g. name@example.com.';
if (message) {
input.setAttribute('aria-invalid', 'true');
error.textContent = message;
error.hidden = false;
} else {
input.removeAttribute('aria-invalid');
error.textContent = '';
error.hidden = true;
}
return message === '';
}
const fields = document.querySelectorAll('form [data-validate]');
fields.forEach((input) => {
input.addEventListener('blur', () => validateField(input));
input.addEventListener('input', () => {
if (input.hasAttribute('aria-invalid')) validateField(input);
});
});
document.querySelector('form').addEventListener('submit', (e) => {
e.preventDefault();
let firstBad = null;
fields.forEach((input) => {
if (!validateField(input) && !firstBad) firstBad = input;
});
if (firstBad) firstBad.focus();
else e.target.submit();
});
Thirty lines, no dependencies, and it covers the interaction most forms get wrong.
Server-side, always
Client validation is a courtesy layer, not a boundary. Everything gets re-validated on the server: required fields, formats, lengths, authorization (can this user edit this record?), and business rules.
Design the server response so the client can re-render errors without losing input — a structured payload beats an HTML fragment for anything beyond a simple form:
{ "errors": { "email": "That email is already registered." } }
And accept input slightly more loosely than you display it: trim whitespace, treat emails case-insensitively, accept phone numbers with punctuation that you normalize yourself. Users should not have to guess your parser’s preferences.
The short version
Validate on blur. Re-check instantly once an error exists. Wire the message to the field with aria-describedby and aria-invalid. Say what right looks like. Focus the first invalid field on submit. Re-validate everything on the server.
None of it is novel. All of it is skipped constantly — which is why a form that simply behaves like this feels better than most of the web, at essentially no cost.