Sub topic 2
Validating Each Step Before Advancing
Assume you know basic programming, form fields, and application state. A multi-step flow should advance only after the current step accepts its data. Keep validation close to the step that owns the fields. This prevents navigation code from becoming a collection of special cases.
Validate before changing flow state
A step can return a list of errors. An empty list means the data is valid. The navigation function validates first, then chooses the next step.
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: (data) =>
/^\S+@\S+\.\S+$/.test(data.email ?? "")
? []
: ["Enter a valid email address."],
next: (data) =>
data.accountType === "business" ? "company" : "review",
},
company: {
id: "company",
validate: (data) =>
data.company?.trim()
? []
: ["Enter your company name."],
next: () => "review",
},
review: {
id: "review",
validate: () => [],
next: () => null,
},
};
function advance(state: FlowState): FlowState {
const step = steps[state.current];
const errors = step.validate(state.data);
if (errors.length > 0) {
return { ...state, errors };
}
const next = step.next(state.data);
if (next === null) return { ...state, errors: [] };
return {
...state,
current: next,
history: [...state.history, state.current],
errors: [],
};
}The current step stays visible when validation fails. Preserve its data and display the returned errors. Clear errors after successful validation so old messages do not appear on a later step.
Show errors users can fix
An error should identify the field, explain the problem, and give a correction. Place the message near the field and move focus to the first invalid field. Do not replace the user’s input or silently discard it.
Branch on earlier answers
The account step branches using accountType. Business users visit company; other users go directly to review. The branch is data-driven because next belongs to the step definition.
Exercise
What should happen when the user selects “business” but leaves the company name empty?
Show answer
Keep the user on the company step, preserve the input, and show an error asking for the company name.