Sub topic 5
Validating Each Step Before Advancing
This chapter assumes you know the flow state model from earlier in the tutorial: a current step id, a history stack, and a data record. You should also be comfortable with TypeScript types and with how a form field maps to a key in data.
Why validate per step
A guided flow asks for a little information at a time. If you validate only at the end, a user can enter a bad email on step one, answer six more steps, and then be sent back. Validating each step before advancing has three benefits:
- Errors appear next to the input that caused them.
- Later steps can rely on earlier data being well formed.
- The user never sees a screen whose questions depend on an answer you already know is invalid.
The rule is simple: Next is a gate. The flow moves to another step only if the current step's data passes that step's own checks.
What a step validator is
In the model used here, each step owns a validate function. It takes the whole data record and returns a list of error messages. An empty list means the step is valid.
type Data = Record<string, string>;
type Step = {
id: string;
validate(data: Data): string[];
next(data: Data): string | null;
};
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,
},
};Three design points are worth noting.
- The validator is a pure function. It reads data and returns messages. It does not touch the screen or change state. This makes it easy to test and to call from places other than the Next button.
- The validator receives all the data, not just its own fields. Some rules need earlier answers. A company step may require a tax id only when
accountTypeis"business". - Validation and branching are separate.
validatedecides whether you may leave.nextdecides where you go. Keeping them apart means a branch is never chosen from invalid data.
Gating the advance
The advance function runs the current step's validator and moves forward only when the result is empty.
type FlowState = {
current: string;
history: string[];
data: Data;
errors: string[];
};
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: [],
};
}On failure the function returns the same step with errors filled in. It does not change current or history. On success it clears old errors. If it did not, a message from a previous attempt could still be on screen after the user fixed the problem.
Building validators from small rules
Writing a regular expression inline for every field gets repetitive. A small set of composable rules keeps validators short and messages consistent.
type Data = Record<string, string>;
type Rule = (d: Data) => string | null;
// Returns the first failing message for one field, or null.
function field(...rules: Rule[]): Rule {
return (d) => {
for (const rule of rules) {
const message = rule(d);
if (message !== null) return message;
}
return null;
};
}
// Combines field rules into a step validator that returns a list.
function check(...rules: Rule[]): (d: Data) => string[] {
return (d) =>
rules
.map((rule) => rule(d))
.filter((message): message is string => message !== null);
}
const required =
(key: string, message: string): Rule =>
(d) =>
(d[key] ?? "").trim() ? null : message;
const pattern =
(key: string, re: RegExp, message: string): Rule =>
(d) =>
re.test(d[key] ?? "") ? null : message;
const validateAccount = check(
field(
required("email", "Enter your email address."),
pattern("email", /^\S+@\S+\.\S+$/, "Enter a valid email address.")
),
field(required("accountType", "Choose an account type."))
);
console.log(validateAccount({ email: "", accountType: "personal" }));
// ["Enter your email address."]
console.log(validateAccount({ email: "[email protected]", accountType: "" }));
// ["Choose an account type."]
console.log(validateAccount({ email: "[email protected]", accountType: "business" }));
// []field stops at the first failing rule for one field. Without it, an empty email would report both "Enter your email address." and "Enter a valid email address.", which says the same thing twice. check still reports one message per field, so a user with two bad fields sees both problems at once.
Kinds of rules
Not every rule is the same, and the differences affect where you put the check.
| Kind | Example | Where it runs |
|---|---|---|
| Presence | Company name is not blank | Step validator |
| Format | Email has an at sign and a domain | Step validator |
| Cross-field | End date is after start date | Step validator, reading two keys |
| Conditional | Tax id is required for business accounts | Step validator, reading an earlier answer |
| Remote | Username is not already taken | Server call, often asynchronous |
Presence, format, cross-field, and conditional rules are synchronous and cheap, so they belong in the step validator. Remote rules need a network call, which changes the flow in the next section.
Remote and asynchronous checks
A username availability check cannot be a pure function. There are two common approaches.
- Check on Next. Disable the button, call the server, then either advance or show the error. This is simple. The user waits at the gate.
- Check while typing, and recheck on Next. Show early feedback after a short pause, but never trust it as the final answer. The name may be taken between the early check and the Next press.
Whichever you pick, three things matter:
- Show a pending state so the user knows the gate is working and does not press Next twice.
- Ignore stale responses. If the user edits the field while a request is in flight, the old response must not change the current screen. Compare the value you checked with the current value before applying the result.
- Treat a failed request as a distinct outcome. A timeout is not "invalid". Show "We could not check this right now. Try again." and let the user retry. Do not block them with a message that blames their input.
Even with a remote check, the server must run the same rule again at final submission. A client-side gate improves the experience and does not enforce anything.
Validation and Back
Back should not be gated by validation. A user who wants to return to the previous step is often doing so because they are stuck or have changed their mind. Blocking them because the current step is half-filled is frustrating.
The back function below pops the history stack without running any validator.
function back(state: FlowState): FlowState {
const previous = state.history[state.history.length - 1];
if (previous === undefined) return state;
return {
...state,
current: previous,
history: state.history.slice(0, -1),
errors: [],
};
}Two details follow from this:
- Keep the partial input. Going back must not erase what the user typed on the step they left. The
datarecord is untouched, so they find it again when they return. - Clear the errors. The old message belongs to the step they left. It would be wrong on the previous screen.
Stale data after a branch changes
Branching creates a subtle validation problem. Suppose a user chooses business, fills in the company step, goes back, and changes the type to personal. The company value is still in data, but the company step is no longer on their path.
Because back removes company from history and next for account now returns "review", the company validator will never run. That is the correct gate behavior. The trouble comes at the end. If you submit all of data, you send a company name for a personal account.
Make the final check walk the actual path, and submit only what the path produced.
type PathFailure = { stepId: string; errors: string[] };
function validatePath(
state: FlowState,
steps: Record<string, Step>
): PathFailure | null {
const path = [...state.history, state.current];
for (const id of path) {
const errors = steps[id].validate(state.data);
if (errors.length > 0) return { stepId: id, errors };
}
return null;
}validatePath checks every step the user passed through, in order, and returns the first failure. If it returns something other than null, send the user to failure.stepId instead of submitting. Per-step validation can miss a problem. For example, a user may change an early answer and then press Next past a step that was valid only for the old answer.
There are two ways to deal with leftover values:
- Prune on submit. Build the payload only from keys owned by steps on the path. This is simple, and it preserves values if the user changes their mind again.
- Prune on change. Delete keys owned by steps that drop off the path as soon as the branch changes. The data stays tidy, but a user who switches back loses what they entered. If you choose this, say so on screen.
Common errors
- Validating only on the last step. The user gets one long list of problems and no context for them. Validate at each gate and again at the end.
- Letting the button decide. If you only disable Next when the form looks invalid, keyboard users and scripts can still call the advance path. Put the gate in
advance, not only in the UI. - Mutating state in the validator. A validator that trims or rewrites values makes testing hard and can overwrite what the user typed. Normalize in a separate step, or at submission.
- Leaving old errors on screen. Clear
errorson every successful move and on Back. - Validating hidden fields. A conditional field that is not visible must not block Next. Make each rule check its own condition first.
- Trusting the client. Every rule that matters for correctness or security must run again on the server.
Testing the gate
Because advance and the validators are pure functions, you can test them without a browser. The checks below cover the gate, the branch, and the path check, using the advance, validatePath, and steps definitions above.
const start: FlowState = { current: "account", history: [], data: {}, errors: [] };
// Gate blocks an invalid step and keeps the position.
const blocked = advance(start, steps);
console.assert(blocked.current === "account");
console.assert(blocked.errors.length === 1);
// Valid personal account skips the company step.
const personal = advance(
{ ...start, data: { email: "[email protected]", accountType: "personal" } },
steps
);
console.assert(personal.current === "review");
console.assert(personal.history.join() === "account");
// Valid business account goes to company, which is then gated.
const toCompany = advance(
{ ...start, data: { email: "[email protected]", accountType: "business" } },
steps
);
console.assert(toCompany.current === "company");
console.assert(advance(toCompany, steps).current === "company");
// Path check finds a bad value on an earlier step.
const tampered: FlowState = {
current: "review",
history: ["account"],
data: { email: "nope", accountType: "personal" },
errors: [],
};
console.assert(validatePath(tampered, steps)?.stepId === "account");Run each path at least once with valid data, invalid data, and a changed earlier answer. These three cases find most gating bugs.
Summary of the approach
- Give each step a pure
validatefunction that returns a list of messages. - Call it inside
advance, so navigation cannot bypass it. - Keep
validateseparate fromnext, so branches are chosen only from valid data. - Do not gate Back, but preserve the data and clear the errors.
- Check the full path again before submitting, and send only data from steps on that path.
- Repeat every important rule on the server.
Exercise
A user chooses "business", completes the company step, goes back to the account step, and changes the type to "personal". They then press Next twice and reach the review step. The data still contains a company name. Which function should detect or handle this when the user submits, and what should happen to the company name?
Show answer
The submission check should walk the real path with validatePath, which uses history plus the current step. The company step is no longer on that path, so its validator does not run and it does not block the user. The payload should be built only from keys owned by steps on the path, so the stale company value is left out. Server-side validation should also reject or ignore a company name on a personal account.
Exercise
Why should the check that blocks Next live inside advance and not only in the code that disables the Next button?
Show answer
A disabled button only affects clicks in one interface. Keyboard shortcuts, form submission by pressing Enter, scripts, and other callers can still invoke the advance path. If advance runs the validator itself, no caller can move the flow forward from an invalid step.
Exercise
A username check on the server times out when the user presses Next. What should the flow do, and what should it avoid doing?
Show answer
It should stay on the step, clear the pending state, and show a message that the check could not be completed, with a way to retry. It should avoid reporting the username as invalid or taken, since the timeout says nothing about the input. It should also avoid advancing as if the check had passed, because the server must still confirm availability at submission.