Sub topic 2
Writing and presenting error messages
This chapter assumes you know basic HTML form elements (input, label, select, button), basic TypeScript, and how a browser submits form data.
Writing and presenting error messages
An error message should say what is wrong and how to fix it. "Invalid input" fails that test. "Enter an email address in the format [email protected]." passes it.
Link each message to its field with aria-describedby, and set aria-invalid="true" on the input so screen readers announce the problem.
<label for="email">Email address</label>
<input id="email" name="email" type="email" autocomplete="email"
aria-describedby="email-error" aria-invalid="true">
<p id="email-error">Enter an email address in the format [email protected].</p>Conditional fields and dependent logic
A hidden field must not be validated or submitted. Give each field a rule for when it is visible, then filter values through that rule before validation and submission.
type Values = Record<string, string>;
type Field = { name: string; visibleWhen?: (v: Values) => boolean };
const fields: Field[] = [
{ name: "delivery" },
{ name: "address", visibleWhen: (v) => v.delivery === "ship" },
];
function activeValues(values: Values): Values {
const result: Values = {};
for (const f of fields) {
if (!f.visibleWhen || f.visibleWhen(values)) {
if (f.name in values) result[f.name] = values[f.name];
}
}
return result;
}Deciding what goes in each step
Group fields that users answer together and that depend on the same earlier answer. Place a question in an earlier step when later steps depend on it. Keep each step short enough to finish without losing context, and put the review step last.
Modeling the flow as a state machine
A state machine names every step and allows only specific moves between them. Forward moves are blocked while the current step has errors. Back moves keep the entered values.
const steps = ["account", "details", "review"] as const;
type StepId = (typeof steps)[number];
function next(step: StepId, valid: boolean): StepId {
if (!valid) return step;
const i = steps.indexOf(step);
return steps[Math.min(i + 1, steps.length - 1)];
}
function back(step: StepId): StepId {
const i = steps.indexOf(step);
return steps[Math.max(i - 1, 0)];
}Navigation, back button, and progress indicators
Show progress as text, such as "Step 2 of 3", and mark the current step with aria-current="step". Keep the Back button available on every step after the first, and never clear values when the user goes back.
Exercise
A user fills in the Details step, goes Back to Account, changes the email, and returns to Details. Which function should keep the Details values, and why?
Show answer
The reducer or state store should keep the values in one object that every step reads. The back function only changes the step name, so the Details values remain in place. Clearing them on Back would force the user to retype their answers.