Sub topic 5
Writing and presenting error messages
This chapter assumes you know basic HTML form elements, can read TypeScript, and understand how a browser submits form data. It also assumes you have read the previous chapter on validation timing. That chapter decided when a rule runs. This chapter decides what the user sees when a rule fails, and how they get back to a valid form.
What an error message has to do
An error message has one job: help the user fix the problem. A good message answers three questions.
- Where is the problem? Which field, and which step.
- What is wrong? In the user's terms, not the system's.
- How do I fix it? An example or a rule the user can act on.
Compare two messages for the same failure.
| Weak message | Better message | Why it is better |
|---|---|---|
| Invalid input | Enter an email address in the format [email protected]. | Names the field's expected format and shows an example. |
| Error 422 | We could not save your address. Check the postcode and try again. | Uses plain words and names the next action. |
| Password does not meet requirements | Use at least 12 characters. | States the one rule that failed. |
| Wrong! | Enter your date of birth as day, month, year. | Does not blame the user and gives the format. |
The same wording should appear everywhere that error is shown: inline, in a summary, and in an announcement for screen readers. If the three places say different things, users lose trust in all of them.
Rules for writing the text
- Say what to do, not only what went wrong. "Enter your full name." beats "Name is required."
- Be specific about the failing rule. If a password needs 12 characters and a number, and the user has 12 characters, report only the missing number.
- Use the field's visible label in the message, so the message still makes sense when it is read away from the field, for example in a summary list.
- Do not blame. Write "Enter a date in the future", not "You entered an invalid date".
- Avoid codes, jargon, and internal field names such as
addr_line_2. - Do not rely on color or an icon alone. The text must carry the meaning.
- Keep each message to one sentence where you can.
Different failures need different tones. A missing required field is routine. A rejected payment is stressful. Keep the first short and neutral, and for the second say what happened, whether money was taken, and what the user can try next.
One message per rule, defined in one place
Messages scatter easily across components. Keep them next to the rules, so a copy change touches one file and the inline text and summary text cannot drift apart.
type FieldError = {
field: string;
label: string;
message: string;
};
type Rule = {
field: string;
label: string;
test: (value: string) => boolean;
message: string;
};
const rules: Rule[] = [
{
field: "email",
label: "Email address",
test: (v) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v),
message: "Enter an email address in the format [email protected].",
},
{
field: "name",
label: "Full name",
test: (v) => v.trim().length > 0,
message: "Enter your full name.",
},
];
function collectErrors(values: Record<string, string>): FieldError[] {
const errors: FieldError[] = [];
for (const rule of rules) {
if (!rule.test(values[rule.field] ?? "")) {
errors.push({ field: rule.field, label: rule.label, message: rule.message });
}
}
return errors;
}
console.log(collectErrors({ email: "not-an-email", name: "Ada" }));Each rule carries its own label, so the summary can link to the right field without a second lookup. A field with several failing rules can still show only the first one, which keeps the screen calm. Return the rest after the user fixes it.
Presenting errors: inline and summary
Two patterns work together on longer forms.
- Inline errors sit directly under the field they describe. The user sees the problem next to the place to fix it.
- An error summary sits at the top of the form or step. It lists every error as a link that moves focus to the failing field.
Use both when a step can have more than one error or when the step is taller than the screen. On a short form with one field, inline alone is enough.
The wiring matters as much as the text. The earlier anatomy chapter showed how aria-describedby links a hint and an error to an input. This is the same pattern applied to an error.
<div>
<label for="email">Email address</label>
<input id="email" name="email" type="email" autocomplete="email" required
aria-describedby="email-hint email-error" aria-invalid="true">
<p id="email-hint">We only use this to send your receipt.</p>
<p id="email-error">Enter an email address in the format [email protected].</p>
</div>Three details are easy to miss:
aria-invalid="true"should be set only while the field has an error. Set it on a pristine field and screen readers announce a problem the user has not caused.- When the error clears, remove its element, or remove its id from
aria-describedby. A stale reference to a missing id is silently ignored, but a stale visible message is not. - Put the error text in the DOM as real text. Text added through CSS
contentis not reliably announced.
Moving focus after a failed submit
When the user presses Next and validation fails, the page must tell them. A sighted user may not see an error that appeared below the fold, and a keyboard or screen reader user gets no signal at all unless you provide one.
The usual approach is to move focus to the error summary, which has a heading such as "There is a problem". The summary's links then move focus to each field. If you have no summary, move focus to the first invalid field.
type FieldError = { field: string; label: string; message: string };
function renderSummary(container: HTMLElement, errors: FieldError[]): void {
container.replaceChildren();
if (errors.length === 0) {
container.hidden = true;
return;
}
const heading = document.createElement("h2");
heading.textContent = "There is a problem";
const list = document.createElement("ul");
for (const error of errors) {
const item = document.createElement("li");
const link = document.createElement("a");
link.href = `#${error.field}`;
link.textContent = error.message;
link.addEventListener("click", (event) => {
event.preventDefault();
document.getElementById(error.field)?.focus();
});
item.append(link);
list.append(item);
}
container.append(heading, list);
container.hidden = false;
container.tabIndex = -1;
container.focus();
}The tabIndex = -1 makes the container focusable by script without adding it to the tab order. Without it, focus() does nothing on a plain div. The link handler is needed because a plain #id link scrolls to the field but does not always move keyboard focus to it.
Moving focus has a cost: it interrupts whatever the user was doing. Do it on submit and step changes, which are explicit user actions. Do not do it on every keystroke or on blur, where it would steal focus from the field the user is moving to.
Live announcements and timing
If you validate on blur or on input, errors appear without any navigation. Sighted users see them. Screen reader users hear nothing unless the page announces the change. Two options exist:
- Let the error in
aria-describedbybe read when the field next receives focus. This is quiet and sufficient for validation on blur. - Put errors in an element with
role="alert"oraria-live="polite"so they are announced as they appear. Use this sparingly. Several alerts in a row talk over each other.
A good default: validate on blur, show the inline error, and announce through the summary only on submit or step change.
Also avoid showing an error before the user has had a chance to finish. An "invalid email" message that appears after typing the first character is noise. This is why the form state chapter tracked a touched flag per field. Show an error only when the field is touched or the user has attempted to move forward.
Recovering from the error
Showing an error is half the work. The other half is making the fix cheap.
- Keep the user's input. Never clear a field because it failed. The user needs to see what they typed to correct it.
- Clear the error when the cause is fixed. Re-run the rule on input once a field is in an error state, so the message disappears as soon as the value is valid. This is sometimes called "reward early, punish late".
- Do not move the layout unexpectedly. An error that pushes the Next button down just as the user clicks it causes a missed click. Reserve space or place errors above the button.
- Accept reasonable variants. If a phone number can have spaces or dashes, normalize them instead of rejecting them. Every rejection you avoid is an error message you do not need to write.
- Point to the step. In a multi-step flow, a failure found at the review step needs a link back to the step that owns the field. Include the step name in the summary entry, and keep entered values when navigating back.
Server errors need the same treatment. A server may reject a value your client rules accepted, for instance an email address that is already registered. Map the server's response to a field error and display it with the same inline and summary components. Do not show a generic banner when the server told you which field failed. Errors that cannot be tied to a field, such as a network failure, belong in a form-level message. The submission chapter covers retries.
Common mistakes
- Using a toast or
alert()for validation errors. Toasts disappear before the user can read them and are not attached to a field. - Showing only a red border. Color alone is not accessible.
- Writing placeholder text as the instruction, then losing it once the user types.
- Listing every possible rule up front and then repeating them in the error. State the rule in the hint, and the failing part in the error.
- Disabling the Next button until the form is valid. The user cannot tell why it is disabled. Leave it enabled and explain the problem when pressed.
- Showing the same error twice for screen readers, once from
aria-liveand once from focus moving to the summary.
Summary
Write each message to say where, what, and how to fix it. Keep the text next to the rule so every surface shows the same words. Show errors inline and in a summary, link them to their fields, and move focus only after an explicit action. Keep the user's input, clear errors when they are fixed, and treat server errors with the same components as client errors.
Exercise
A user submits step 2 of a checkout form with an empty "Full name" field and an invalid postcode. Describe what the page should do after the submit, including where focus goes, what each error says, and what happens to the values already entered.
Show answer
The page keeps all entered values and shows one inline error under each failing field. Examples are "Enter your full name." and "Enter a postcode in the format SW1A 1AA." It also shows a summary at the top of the step with the heading "There is a problem". The summary lists both messages as links, and each link moves focus to its field. Focus moves to the summary after the submit, because the submit was an explicit action. Each failing input gets aria-invalid="true" and an aria-describedby reference to its error. The user stays on step 2. The Next button stays enabled, and each error clears as soon as its field becomes valid.
Exercise
Your server rejects a signup because the email address is already registered, although the client rule accepted it. Where and how should you show this, and why is a generic "Something went wrong" banner a poor choice?
Show answer
Map the server response to a field error on the email field and render it through the same inline and summary components, with text such as "That email address is already registered. Sign in or use a different address." Then move focus to the summary or the field. A generic banner does not say which field to fix, is not linked to the input, and gives screen reader users no field-level association. Keep a form-level message only for failures that cannot be tied to a field, such as a lost network connection.