Stepperize v9Explore the changes
Skip to Content
Stepperize

Schemas and validation

Give a step a schema, and next() validates it for you.

Stepperize can validate a step's data without becoming a form library, and without tying you to one validation library. This page explains how, and the one distinction that makes it click: what a step stores is a draft, and the validated output is kept next to it.

Standard Schema, not a specific library

A step may carry a schema. Any Standard Schema works, so Zod, Valibot and ArkType are interchangeable, and can even be mixed in one flow.

import { defineStepper } from "@stepperize/react";
import { type } from "arktype";
import * as v from "valibot";
import { z } from "zod";

const checkout = defineStepper([
  { id: "shipping", schema: z.object({ address: z.string().min(1) }) }, // Zod
  { id: "payment", schema: v.object({ card: v.pipe(v.string(), v.nonEmpty()) }) }, // Valibot
  { id: "review", schema: type({ accepted: "boolean" }) }, // ArkType
]);

Stepperize has no dependency on any of them. It only reads the ~standard property every compliant schema exposes.

A schema does two things for its step:

  1. It types the step's data. stepper.data.shipping is the schema's input type, and so is the argument of setData("shipping", ...).
  2. It is what next() validates. A step that fails its schema cannot be left through next().

Try it: one API, three libraries

Each demo is a one-step flow. Typing calls next() with the value and shows what it resolved with.

Zod

…
const form = defineStepper([
  { id: "user", schema: z.object({ username: z.string().min(3, "At least 3 characters") }) },
]);

const result = await form.create().next({ username: "ab" });
// { accepted: false, reason: "invalid", issues: [{ message: "At least 3 characters", path: ["username"] }] }

What next() does

const result = await stepper.next({ address });
  1. Takes the data you pass as the data of the current step. Without an argument, it takes what the step already has stored.
  2. Validates it against the step's schema. Async schemas are awaited.
  3. If it is valid, marks the step complete and moves on.
  4. If it is not, stays on the step, keeps the data you passed, and remembers the issues.

It never throws for an invalid step:

if (!result.accepted && result.reason === "invalid") {
  result.issues; // [{ message: "Address is required", path: ["address"] }]
}

Validation runs for next() only. prev() and goTo() leave a step without checking it, which is why going back is never blocked by a half-filled form.

Show the issues

issues(id?) returns the issues of the last rejected next() for a step, the current one by default. They are cleared as soon as that step's data changes, so an error goes away when the person starts fixing it.

function Errors() {
  const stepper = checkout.useStepperContext();
  return (
    <ul>
      {stepper.issues()?.map((issue) => (
        <li key={issue.message}>{issue.message}</li>
      ))}
    </ul>
  );
}

Each issue has a message and an optional path, as Standard Schema defines them. Forms shows how to place them next to their fields.

This is the complete pattern in a real checkout. Press Continue with empty fields, then start typing:

Where should we ship?

Draft data and validated output

stepper.data holds whatever each step last saved. It is a scratchpad, typed as the schema's input, and it may be partial or invalid at any time.

stepper.data.shippingstepper.output.shipping
What it isThe stored draftWhat the schema produced when next() completed the step
Typed asSchema input, or undefinedSchema output, or undefined
GuaranteesNoneParsed and valid; present only while the step is complete
Use it forFilling forms, saving draftsSubmitting, review screens that show the final values

Stepperize does not replace the draft with the schema's output: your fields keep reading what the person typed. The output lives in stepper.output, so a schema that transforms or coerces (trimming, string to number, defaults) never has to be run a second time by you.

const shippingSchema = z.object({
  zip: z.string().trim().regex(/^\d{5}$/),
  floor: z.coerce.number().default(0),
});

await flow.next({ zip: " 90210 ", floor: "3" });

flow.data.shipping; // { zip: " 90210 ", floor: "3" }: as typed
flow.output.shipping; // { zip: "90210", floor: 3 }: as validated

The same output is the first argument of onFinish, and what a next branch receives for the step being left:

checkout.useStepper({
  onFinish: (output, data) => {
    api.createOrder(output); // every complete step, validated
    data; // every step as typed, complete or not
  },
});

A step has output only while it is complete. Change its data and both go away until next() validates it again. Steps that were restored as complete have none until the flow finishes: a snapshot stores the draft, and next() on the final step validates those steps once more before calling onFinish. If one of them no longer passes, for example because the schema changed since the draft was saved, the flow does not finish: the result is invalid, and stepper.issues(id) has the issues for that step.

Steps without a schema

They are first-class. Their data is typed unknown, and next() always passes them. Intros, confirmations and review screens need nothing more.

const wizard = defineStepper([
  { id: "intro" }, // next() always moves on
  { id: "details", schema: detailsSchema }, // validated
]);

Async validation

A schema can be asynchronous, for example to ask the server whether a username is free. next() awaits it, stepper.isPending is true meanwhile, and other moves are refused with reason: "pending".

const account = z.object({
  username: z
    .string()
    .min(3)
    .refine(async (value) => !(await api.isTaken(value)), "That username is taken"),
});

Synchronous schemas never set isPending, so there is no flicker.

Validate without moving

stepper.validate() runs the schema of the current step on its stored data and stays where it is. It resolves with the issues, or undefined when the data is valid.

async function onBlur() {
  stepper.setData("shipping", values);
  const issues = await stepper.validate();
  if (issues) showErrors(issues);
}

The result is remembered the same way a rejected next() is, so stepper.issues() returns those issues on the next render, until the data changes. Pass an id to check another step, for example every step from a review screen:

for (const step of stepper.steps) {
  const issues = await stepper.validate(step.id);
  if (issues) return stepper.goTo(step.id);
}

validate() only checks. It does not mark the step complete, does not run the guard and does not call onChange: completing a step is what next() does.

It validates what the flow has stored, so save the values first with setData when they live in your form library. To check a value that is not in the flow at all, use the schema you already have: shippingSchema.safeParse(values).

Checks that are not a schema

For anything a schema cannot express (a server-side rule, a confirmation), use a guard. It runs after validation and can cancel the move.

What validation is, and is not

  • It tells you whether a step's data satisfies its schema, and blocks next() when it does not.
  • It returns the issues, and keeps them available through issues().
  • It works with any Standard Schema, with no runtime dependency.
  • It does not render errors, track touched or dirty fields, or register inputs. That is your form library's job, or a few lines of your own.
  • It does not make Stepperize a form library. Stepperize owns the flow; validation is the gate between two steps.

Next: branching, or the Forms section to connect a form library.

Edit on GitHub

Last updated on

On this page