Sub topic 6
Showing errors users can fix
This chapter assumes you have read the earlier chapters on flow state and per-step validation. You should know the FlowState type, the Step type with its validate function, and how advance blocks navigation when validation fails. Here we focus on what happens after validation fails: how the error is shaped, where it appears, and how the user recovers.
Why error messages need design
In the earlier chapter, validate returned an array of strings, and advance stored them in state.errors. That is enough to block navigation. It is not enough to help a person.
A list of strings has three weaknesses:
- It does not say which field each message belongs to.
- It gives the interface no stable way to move focus to the problem.
- It leaves the wording to whoever wrote the rule, with no shared guidance.
An error is useful when the user can answer three questions without guessing: what is wrong, where it is wrong, and what to do next. The rest of this chapter turns those three questions into data and code.
Attaching errors to fields
The first change is to replace plain strings with a structure that names the field. Keep it small.
type FieldError = {
field: string;
message: string;
};
type StepErrors = FieldError[];
function validateAccount(data: Record<string, string>): StepErrors {
const errors: StepErrors = [];
if (!/^\S+@\S+\.\S+$/.test(data.email ?? "")) {
errors.push({
field: "email",
message: "Enter an email address like [email protected].",
});
}
return errors;
}
console.log(validateAccount({ email: "ana" }));The field value matches the input's name. With it, the interface can place each message next to its input, mark that input as invalid, and send keyboard focus to the first problem.
In the FlowState type from the earlier chapter, change errors: string[] to errors: FieldError[]. The Step.validate signature changes the same way. The advance function does not need any other change, because it only checks errors.length.
Writing messages that can be acted on
Compare these messages for the same failure.
| Weak message | Better message | Why it is better |
|---|---|---|
| Invalid input | Enter an email address like [email protected]. | Says what to do and shows the shape. |
| Error in field | Enter your company name. | Names the missing item. |
| Password rejected | Use at least 12 characters. You have 8. | Gives the rule and the current state. |
| Bad date | Enter a date in the format DD/MM/YYYY. | States the expected format. |
A few rules cover most cases:
- Say what the user should do, not only what they did wrong.
- Use the label the user sees. If the field is labelled "Company name", do not call it "organization" in the error.
- State the rule when the user cannot guess it, such as a length limit or a format.
- Do not blame. "Enter a valid email address" is better than "You entered an invalid email address".
- Do not rely on color or an icon alone to show that something is wrong.
Write messages in the validation code or in a message table next to it, not in the view. This keeps the wording reviewable in one place and lets tests check the exact text.
Message tables
When the same rule appears in several steps, such as a required field, define the wording once.
type FieldError = { field: string; message: string };
const messages = {
required: (label: string) => `Enter ${label}.`,
tooShort: (label: string, min: number, actual: number) =>
`${label} must be at least ${min} characters. You have ${actual}.`,
};
function requireText(
data: Record<string, string>,
field: string,
label: string
): FieldError[] {
const value = (data[field] ?? "").trim();
return value ? [] : [{ field, message: messages.required(label) }];
}
console.log(requireText({ company: " " }, "company", "your company name"));Note the .trim(). A value made only of spaces looks filled in to the user but is empty to your rules. Decide once whether to trim, and apply that decision everywhere.
When to show errors
There are three common timings, and each has costs.
| Timing | Behavior | Risk |
|---|---|---|
| On advance | Errors appear when the user presses Next. | The user finds out late, but is never interrupted mid-typing. |
| On blur | Errors appear when the user leaves a field. | Good feedback, but it can flag a field the user has not finished with. |
| On every keystroke | Errors update as the user types. | Shows "invalid email" after the first character. This is noisy and distracting. |
For a step-based flow, a sound default is: validate on advance, and after the first failed attempt, re-validate a field when it changes so the message disappears as soon as the problem is fixed. This avoids scolding someone who has not yet had the chance to finish, and it removes stale errors quickly.
Do not show errors for steps the user has not reached. The user cannot fix a problem on a screen they have not seen.
Recovery: keeping what the user typed
An error screen must never erase input. When advance returns early with errors, it spreads the old state and keeps data intact. Preserve that behavior in the view as well. Re-render inputs from state.data, not from defaults.
Two further recovery points matter in a flow:
- Back navigation. The
backfunction clearserrors. That is correct, because the errors belonged to the step being left. The data stays instate.data, so returning to the step shows the earlier values. - Errors from earlier steps. If a later step changes an answer that an earlier step depended on, the earlier step may become invalid. Re-validate affected steps before submission, covered in the review chapter.
Helpers for the view
Keep the view simple by giving it two small functions: one to find the error for a field, and one to find the first field with an error.
type FieldError = { field: string; message: string };
function errorFor(errors: FieldError[], field: string): string | undefined {
return errors.find((e) => e.field === field)?.message;
}
function firstErrorField(errors: FieldError[]): string | undefined {
return errors[0]?.field;
}
const errors: FieldError[] = [
{ field: "email", message: "Enter an email address like [email protected]." },
];
console.log(errorFor(errors, "email"));
console.log(firstErrorField(errors));
console.log(errorFor(errors, "company"));The order of the errors array matters. firstErrorField assumes the array follows the order of the fields on screen. Build errors in that order inside validate, and the first one will be the one nearest the top.
Combining a summary with inline messages
For a step with several fields, show two things:
- An inline message directly under each invalid field.
- A summary at the top of the step that lists all problems, with each item linking to its field.
The summary helps people who use screen magnifiers or screen readers, who may not see the inline messages without searching. It also gives everyone a count of what remains.
type FieldError = { field: string; message: string };
function summaryItems(errors: FieldError[]): { href: string; text: string }[] {
return errors.map((e) => ({ href: "#" + e.field, text: e.message }));
}
console.log(
summaryItems([
{ field: "email", message: "Enter an email address like [email protected]." },
{ field: "company", message: "Enter your company name." },
])
);Each summary link points at the input's id. For this to work, each input must have an id equal to its field name.
For a step with a single field, a summary and an inline message say the same thing twice. In that case, one message is enough, as long as focus moves to it.
Moving focus after a failed attempt
When the user presses Next and validation fails, nothing visible may change except new text. A keyboard or screen reader user can miss that entirely. Move focus to the error summary, or to the first invalid field when there is no summary.
type FieldError = { field: string; message: string };
function focusAfterFailure(errors: FieldError[], doc: Document): void {
if (errors.length === 0) return;
const summary = doc.getElementById("error-summary");
if (summary) {
summary.focus();
return;
}
doc.getElementById(errors[0].field)?.focus();
}The summary element needs tabindex="-1" so that it can receive focus from code without joining the normal tab order. The next chapters on accessibility return to focus management for successful transitions as well.
Connect each inline message to its input with aria-describedby, and set aria-invalid="true" on invalid inputs. Remove both when the error clears, so assistive technology does not keep announcing a problem that is gone.
Errors that are not validation errors
Validation errors are the user's to fix. Some failures are not. A network call can fail when the flow checks whether a username is taken, or when it submits. Treat these separately:
- Keep them out of
state.errors, or give them a distinct type, so the view does not point at a field that is not at fault. - Say plainly that the problem is not the user's input: "We could not check that username. Try again."
- Offer a way to retry without retyping anything.
A short union type keeps the two kinds apart.
type FieldError = { field: string; message: string };
type SystemError = { kind: "system"; message: string; retryable: boolean };
type StepProblem =
| { kind: "field"; errors: FieldError[] }
| SystemError;
function describe(problem: StepProblem): string {
if (problem.kind === "system") {
return problem.retryable
? problem.message + " Try again."
: problem.message + " Contact support.";
}
return problem.errors.length + " field(s) need attention.";
}
console.log(describe({ kind: "system", message: "We could not save.", retryable: true }));Common mistakes
- Clearing the form on error. Always re-render from
state.data. - Generic messages. "Invalid input" forces the user to guess.
- Errors on untouched fields at first render. A step should open clean.
- Stale errors. If you do not clear an error when the field changes or the user goes back, the screen contradicts itself.
- Message order that does not match screen order. Focus then jumps to an unexpected place.
- Server-side rules missing on the client. If the server rejects something the client allowed, map the server's response back onto
FieldErrorvalues so the same display code works.
Exercise
A step has fields for "password" and "confirm". The user presses Next with a 6-character password that does not match the confirmation. Using the FieldError type, what errors would validate return, in what order, and where should focus go?
Show answer
Return two errors in screen order: { field: "password", message: "Password must be at least 12 characters. You have 6." } and { field: "confirm", message: "Enter the same password again." }. Focus moves to the error summary if the step has one, otherwise to the "password" input, because it is first in the array. The typed values stay in state.data, so nothing is erased.
Exercise
Why should a flow re-validate a field on change only after the first failed attempt, rather than from the first keystroke?
Show answer
Validating from the first keystroke shows errors such as "invalid email" while the user is still typing a correct value, which is noisy and discouraging. Waiting for a failed attempt means the user has already been told about the problem, so live re-validation then serves one purpose: removing the message as soon as the problem is fixed.