Not only React anymoreStepperize now runs in Vue, Svelte, Solid, Angular, Lit, and HTML
Skip to Content
Stepperize

TanStack Form

A three-step checkout with TanStack Form for Svelte 5, where the form and the step validate with the same Standard Schema.

TanStack Form owns the fields of each step; Stepperize owns the flow, what each step saved and the order sent at the end. TanStack Form takes Standard Schema validators directly, so the schema of a step is also its form's validator, with no adapter.

The code on this page is checked against @tanstack/svelte-form 1.33, Svelte 5.59 and Zod 4.6. It needs no SvelteKit; for form actions and server validation, see Superforms.

Install

npm install @stepperize/svelte @tanstack/svelte-form zod

The flow

checkout.ts
import { defineStepper, type FlowOutput, type Issue } from "@stepperize/svelte";
import { z } from "zod";

export const personalSchema = z.object({
  name: z.string().trim().min(1, "Enter your name"),
  email: z.email("Enter a valid email"),
});

export const shippingSchema = z.object({
  address: z.string().trim().min(1, "Enter your address"),
  zip: z.string().regex(/^\d{5}$/, "Enter a 5-digit ZIP"),
});

export const checkout = defineStepper(
  [
    { id: "personal", title: "Personal", schema: personalSchema },
    { id: "shipping", title: "Shipping", schema: shippingSchema },
    { id: "review", title: "Review" },
  ],
  { linear: true },
);

export type Order = FlowOutput<typeof checkout.steps>;

/** The first issue of each field, keyed by its path: "email", "address.zip". */
export function issuesByField(issues: ReadonlyArray<Issue>) {
  const fields: Record<string, Issue> = {};
  for (const issue of issues) {
    const key = (issue.path ?? [])
      .map((part) => String(typeof part === "object" ? part.key : part))
      .join(".");
    fields[key] ??= issue;
  }
  return fields;
}

issuesByField keeps whole issues, not just their messages: the schema's own errors are issues too, so the markup reads error.message for both.

Complete example

Checkout.svelte
<script lang="ts">
  import { checkout, type Order } from "./checkout";
  import CheckoutSteps from "./CheckoutSteps.svelte";

  // Return the promise: the flow stays pending while it runs, and unfinished if it rejects.
  async function placeOrder(order: Order) {
    const response = await fetch("/api/orders", {
      method: "POST",
      headers: { "content-type": "application/json" },
      body: JSON.stringify(order),
    });
    if (!response.ok) throw new Error("Could not place the order");
  }
</script>

<checkout.Provider onFinish={placeOrder}>
  <CheckoutSteps />
</checkout.Provider>
CheckoutSteps.svelte
<script lang="ts">
  import { checkout } from "./checkout";
  import PersonalStep from "./PersonalStep.svelte";
  import ReviewStep from "./ReviewStep.svelte";
  import ShippingStep from "./ShippingStep.svelte";

  const stepper = checkout.useStepperContext();
</script>

{#if stepper.isFinished}
  <p role="status">Order placed.</p>
{:else}
  <section>
    <h2>{stepper.current.title}</h2>
    {#if stepper.current.id === "personal"}
      <PersonalStep />
    {:else if stepper.current.id === "shipping"}
      <ShippingStep />
    {:else}
      <ReviewStep />
    {/if}
  </section>
{/if}
PersonalStep.svelte
<script lang="ts">
  import { createForm } from "@tanstack/svelte-form";
  import { checkout, issuesByField, personalSchema } from "./checkout";

  const stepper = checkout.useStepperContext();
  // What the step saved: Back and a restored draft open the form filled in.
  // Read once, so the options below do not follow the flow's data.
  const initial = stepper.data.personal ?? { name: "", email: "" };

  const form = createForm(() => ({
    defaultValues: initial,
    validators: {
      // The form checks its fields first, with the step's own schema...
      onSubmit: personalSchema,
      // ...and only then hands them to the step, which saves, validates and moves.
      onSubmitAsync: async ({ value }) => {
        const result = await stepper.next(value);
        if (result.accepted || !result.issues) return;
        // Shaped like the schema's errors, so the markup reads `.message` for both.
        return { fields: issuesByField(result.issues) };
      },
    },
  }));

  const isSubmitting = form.useSelector((state) => state.isSubmitting);
</script>

<form
  novalidate
  onsubmit={(event) => {
    event.preventDefault();
    event.stopPropagation();
    form.handleSubmit();
  }}
>
  <form.Field name="name">
    {#snippet children(field)}
      <label for={field.name}>Name</label>
      <input
        id={field.name}
        name={field.name}
        autocomplete="name"
        value={field.state.value}
        aria-invalid={field.state.meta.errors.length > 0}
        onblur={field.handleBlur}
        oninput={(event) => field.handleChange(event.currentTarget.value)}
      />
      {#each field.state.meta.errors as error}
        <p role="alert">{error?.message}</p>
      {/each}
    {/snippet}
  </form.Field>

  <form.Field name="email">
    {#snippet children(field)}
      <label for={field.name}>Email</label>
      <input
        id={field.name}
        name={field.name}
        type="email"
        autocomplete="email"
        value={field.state.value}
        aria-invalid={field.state.meta.errors.length > 0}
        onblur={field.handleBlur}
        oninput={(event) => field.handleChange(event.currentTarget.value)}
      />
      {#each field.state.meta.errors as error}
        <p role="alert">{error?.message}</p>
      {/each}
    {/snippet}
  </form.Field>

  <button type="submit" disabled={isSubmitting.current}>Continue</button>
</form>
ShippingStep.svelte
<script lang="ts">
  import { createForm } from "@tanstack/svelte-form";
  import { checkout, issuesByField, shippingSchema } from "./checkout";

  const stepper = checkout.useStepperContext();
  const initial = stepper.data.shipping ?? { address: "", zip: "" };

  const form = createForm(() => ({
    defaultValues: initial,
    validators: {
      onSubmit: shippingSchema,
      onSubmitAsync: async ({ value }) => {
        const result = await stepper.next(value);
        if (result.accepted || !result.issues) return;
        return { fields: issuesByField(result.issues) };
      },
    },
  }));

  const isSubmitting = form.useSelector((state) => state.isSubmitting);

  function back() {
    // Keep what was typed here, without validating it. Only when something
    // changed: a new object would make a complete step incomplete.
    if (form.state.isDirty) stepper.setData("shipping", { ...form.state.values });
    stepper.prev();
  }
</script>

<form
  novalidate
  onsubmit={(event) => {
    event.preventDefault();
    event.stopPropagation();
    form.handleSubmit();
  }}
>
  <form.Field name="address">
    {#snippet children(field)}
      <label for={field.name}>Address</label>
      <input
        id={field.name}
        name={field.name}
        autocomplete="street-address"
        value={field.state.value}
        aria-invalid={field.state.meta.errors.length > 0}
        onblur={field.handleBlur}
        oninput={(event) => field.handleChange(event.currentTarget.value)}
      />
      {#each field.state.meta.errors as error}
        <p role="alert">{error?.message}</p>
      {/each}
    {/snippet}
  </form.Field>

  <form.Field name="zip">
    {#snippet children(field)}
      <label for={field.name}>ZIP</label>
      <input
        id={field.name}
        name={field.name}
        inputmode="numeric"
        autocomplete="postal-code"
        value={field.state.value}
        aria-invalid={field.state.meta.errors.length > 0}
        onblur={field.handleBlur}
        oninput={(event) => field.handleChange(event.currentTarget.value)}
      />
      {#each field.state.meta.errors as error}
        <p role="alert">{error?.message}</p>
      {/each}
    {/snippet}
  </form.Field>

  <button type="button" onclick={back}>Back</button>
  <button type="submit" disabled={isSubmitting.current}>Review</button>
</form>
ReviewStep.svelte
<script lang="ts">
  import { checkout } from "./checkout";

  const stepper = checkout.useStepperContext();
  let error = $state("");

  async function placeOrder() {
    error = "";
    try {
      // On the last step, next() runs onFinish and waits for it.
      await stepper.next();
    } catch {
      error = "Could not place the order. Try again.";
    }
  }
</script>

<dl>
  <dt>Personal</dt>
  <dd>{stepper.data.personal?.name} · {stepper.data.personal?.email}</dd>
  <dt>Shipping</dt>
  <dd>{stepper.data.shipping?.address}, {stepper.data.shipping?.zip}</dd>
</dl>
{#if error}<p role="alert">{error}</p>{/if}

<button type="button" disabled={stepper.isPending} onclick={() => stepper.goTo("personal")}>
  Edit details
</button>
<button type="button" disabled={stepper.isPending} onclick={() => stepper.prev()}>Back</button>
<button type="button" disabled={stepper.isPending} onclick={placeOrder}>
  {stepper.isPending ? "Placing order…" : "Place order"}
</button>

Why this works

  • The move is the form's last validator. onSubmit runs the schema first; onSubmitAsync only runs when it passed, and calls next(value). When the step accepts, the next step renders. When it refuses, the issues are returned as field errors and the form stays.
  • isSubmitting covers the move. It is true until onSubmitAsync settles, so the button is disabled while an async rule of the step runs.
  • Back fills the form. initial comes from stepper.data, so going back, or resuming a draft, shows what was saved.
  • The request is part of the last move. onFinish returns the promise of the request: stepper.isPending is true while it runs, a second press is refused, and a failure leaves the flow open for another try.

Which side validates

RunsWhen it fails
TanStack Formvalidators.onSubmit on submit; add onChange or onBlur for earlier feedbackonSubmitAsync does not run, so next() is never called
The step's schemaInside every next()next() returns issues; onSubmitAsync returns them as field errors

Errors that come from the step

A rule that only the step knows, such as an async check against your server, reaches the form through onSubmitAsync: it returns { fields: issuesByField(result.issues) } and TanStack Form shows each issue under its field.

checkout.ts
export const checkout = defineStepper(
  [
    {
      id: "personal",
      title: "Personal",
      // The form keeps `personalSchema`; only the step asks the server.
      schema: personalSchema.refine(async ({ email }) => !(await isRegistered(email)), {
        message: "That email already has an account",
        path: ["email"],
      }),
    },
    { id: "shipping", title: "Shipping", schema: shippingSchema },
    { id: "review", title: "Review" },
  ],
  { linear: true },
);

isRegistered is your own request. The form keeps personalSchema, so typing never calls it; Continue does, once.

Drafts and Back

  • Read the saved values once, outside the options. createForm takes a function and reads it again when the state it uses changes. Reading stepper.data inside it would tie the form's options to the flow's data; const initial = ... reads it once, when the step mounts.
  • Back keeps what was typed, without validating it. setData stores a draft. Only write it when form.state.isDirty: a complete step whose data changes is no longer complete, and in a linear flow neither are the steps after it.
  • Hand the flow a copy. { ...form.state.values } is a plain object of its own.

Pitfalls

  • Calling next() from onSubmit instead. It works for the happy path, but onSubmit has no way to return errors: when the step refuses, nothing is shown unless you write them into the form yourself. A validator returns them.
  • Mixing strings and issues. Errors you return yourself are shown as they are; the schema's are issue objects. Return issues, as issuesByField does, and render error.message for both.
  • form.useStore. It is deprecated in favour of form.useSelector, which returns an object whose current follows the state.
Edit on GitHub

Last updated on

On this page