Sub topic 5
Validating each step before advancing
This chapter assumes you know how flow state is modeled (a current step, collected data, and a history stack) and how forward and back navigation work. It builds on both.
Why validate per step
A guided flow asks for a little input at a time. If you check everything only at the end, a user can reach the last screen and learn that an answer from step one was wrong. Per-step validation moves that feedback to the moment the user tries to leave the step. The rule is simple: the flow advances only when the current step's data is valid.
Validation is not only a user interface concern. Treat it as a gate in the navigation logic, so no code path can skip it.
Put validation in the step definition
Each step declares its own validate function. It takes the collected data and returns a list of error messages. An empty list means the step is valid. This keeps the rules next to the step they belong to, and the navigation code stays generic.
type Data = Record<string, string>;
type Step = {
id: string;
validate(data: Data): string[];
next(data: Data): string | null;
};
type FlowState = {
current: string;
history: string[];
data: Data;
errors: string[];
};
const steps: Record<string, Step> = {
account: {
id: "account",
validate: (d) =>
/^\S+@\S+\.\S+$/.test(d.email ?? "") ? [] : ["Enter a valid email address."],
next: (d) => (d.accountType === "business" ? "company" : "review"),
},
company: {
id: "company",
validate: (d) => ((d.company ?? "").trim() ? [] : ["Enter your company name."]),
next: () => "review",
},
review: {
id: "review",
validate: () => [],
next: () => null,
},
};
function advance(state: FlowState, steps: Record<string, Step>): FlowState {
const step = steps[state.current];
const errors = step.validate(state.data);
if (errors.length > 0) return { ...state, errors };
const nextId = step.next(state.data);
if (nextId === null) return { ...state, errors: [] };
return {
...state,
current: nextId,
history: [...state.history, state.current],
errors: [],
};
}
const start: FlowState = {
current: "account",
history: [],
data: { email: "ana@example", accountType: "business" },
errors: [],
};
const blocked = advance(start, steps);
console.log(blocked.current, blocked.errors); // account ["Enter a valid email address."]
const fixed = advance(
{ ...blocked, data: { ...blocked.data, email: "[email protected]" } },
steps
);
console.log(fixed.current, fixed.history); // company ["account"]The first call fails because ana@example has no dot after the @. The state keeps current at account and stores the error. After the email is corrected, the same call moves the flow to company and records account in the history.
What the gate does
Rules that keep validation reliable
- Validate the current step only. Do not check fields from steps the user has not reached. Otherwise they see errors about fields they cannot yet see.
- Return all errors at once. A step with three bad fields should report all three. Returning only the first forces a retry loop.
- Clear errors on movement. Both
advanceandbackseterrorsto an empty list. Stale messages from a previous step are confusing. - Do not validate on Back. Going back should always work, even if the current step is incomplete. Gating Back traps users.
- Keep validators pure. A function from data to messages is easy to test and has no hidden side effects.
Common errors
The first mistake is validating only in the interface. If the Next button is disabled but advance does not check, a keyboard shortcut, a restored draft, or a test can still skip the gate. Always put the check inside the navigation function.
The second is validating against data that branching has made irrelevant. Suppose a user chooses "business", fills in a company name, then goes back and switches to "personal". The company value is still in data. The company step is no longer on the path, so its validator never runs, but the stale value may still be submitted. Decide how to handle this: either remove values for steps that left the path, or have the final submission read only the data of steps in the history.
The third is checking things a step cannot know. Some rules, such as "this email is not already registered", need a server. Run these checks as an asynchronous part of advancing, and show a pending state while they run. A synchronous validate function should cover only rules that depend on local data.
Exercise
A user selects "business", enters a company name, presses Next to reach review, then goes back twice and changes the account type to "personal". Using the code in this chapter, which step comes after account now, and what could go wrong with the stored company value?
Show answer
The next step is review, because next returns "company" only when accountType is "business". The company value stays in data, so a submission that reads all of data would include a company name for a personal account. Fix it by removing data for steps no longer on the path, or by submitting only data from the steps in the current path.