Skip to content
Marketing block

Multi-Step Form with Validation

A three-step form where each step validates only its own fields, errors are wired to inputs with aria-describedby, and advancing moves focus to the new heading.

373 lineslucide-reactAdded 8 Aug 2026Updated 10 Sept 2026
  • form
  • wizard
  • steps
  • validation
  • multi-step

What's included

  • components/multi-step-form.tsx
  • Needs lucide-react

Works with

  • React
  • Next.js
  • Tailwind CSS
  • TypeScript

npx hoverlab add multi-step-form

Or over MCP, from your editor's agent — no account needed.

License

Free to read, copy and install, for personal and non-commercial projects. Shipping it in client work or a paid product needs Pro ($79 once). The source lands in your repo and stops being ours — no attribution, nothing to upgrade.

Was this useful?

Start a page with this section — add more, order them, and leave with the page source.

Preview

Set up your workspace

  1. 1
  2. 2
  3. 3

Your details

Rendered live in your current theme — this is the same component whose source is below, not a screenshot of it.

Source

components/multi-step-form.tsx
'use client'

/**
 * <MultiStepForm> — a three-step form with a stepper and per-step validation.
 *
 * The pattern exists to make a long form feel finishable. What makes it
 * work is that each step is genuinely complete on its own: you can answer
 * everything visible, and "Continue" is refused only for a field you can
 * currently see. A wizard that fails on step 1 because of something on
 * step 3 is worse than one long page.
 *
 * The accessibility of a stepper is almost always wrong, so:
 *
 *  - The stepper is an ordered list, not a row of divs. Position in a
 *    sequence is the entire meaning, and `<ol>` is what conveys it.
 *  - The current step carries `aria-current="step"`.
 *  - Completed steps say so in text (`sr-only` "completed"), because a
 *    green tick is colour and shape only.
 *  - Errors use `aria-invalid` plus `aria-describedby` pointing at the
 *    message, so the message is read *with* the field rather than being
 *    a red sentence floating nearby.
 *  - Advancing moves focus to the new step's heading, which is what tells
 *    a screen reader anything happened at all. Without it the user presses
 *    Continue and hears silence.
 *
 * Validation is deliberately trivial (required, and an `@` in the email) —
 * this is a layout and a flow, not a schema library. Swap `validateStep`
 * for Zod or your own rules; nothing else needs to change.
 */

import * as React from 'react'
import { Check, ChevronLeft, ChevronRight } from 'lucide-react'

export interface MultiStepValues {
  name: string
  email: string
  company: string
  teamSize: string
  useCase: string
  referral: string
}

export interface MultiStepFormProps {
  heading?: string
  steps?: string[]
  submitLabel?: string
  successMessage?: string
  onSubmit?: (values: MultiStepValues) => void | Promise<void>
  className?: string
}

const DEFAULT_STEPS = ['Your details', 'Your team', 'Finish']

const EMPTY: MultiStepValues = {
  name: '',
  email: '',
  company: '',
  teamSize: '1–10',
  useCase: '',
  referral: '',
}

type Errors = Partial<Record<keyof MultiStepValues, string>>

/** Which fields each step owns — the reason a step can validate itself. */
const FIELDS_BY_STEP: Array<Array<keyof MultiStepValues>> = [
  ['name', 'email'],
  ['company', 'teamSize'],
  ['useCase'],
]

function validateStep(step: number, values: MultiStepValues): Errors {
  const errors: Errors = {}
  for (const field of FIELDS_BY_STEP[step] ?? []) {
    const value = values[field].trim()
    if (!value) {
      errors[field] = 'This field is required.'
    } else if (field === 'email' && !value.includes('@')) {
      errors[field] = 'Enter a valid email address.'
    }
  }
  return errors
}

export function MultiStepForm({
  heading = 'Set up your workspace',
  steps = DEFAULT_STEPS,
  submitLabel = 'Create workspace',
  successMessage = 'Workspace created. Check your email for the invite link.',
  onSubmit,
  className = '',
}: MultiStepFormProps) {
  // Per-instance ids. A literal id in a reusable component is a
  // collision waiting for the second copy on the page — and a <label>
  // then resolves to whichever input rendered first.
  const uid = React.useId()
  const [step, setStep] = React.useState(0)
  const [values, setValues] = React.useState<MultiStepValues>(EMPTY)
  const [errors, setErrors] = React.useState<Errors>({})
  const [done, setDone] = React.useState(false)
  const headingRef = React.useRef<HTMLHeadingElement>(null)

  function set<K extends keyof MultiStepValues>(key: K, value: MultiStepValues[K]) {
    setValues((v) => ({ ...v, [key]: value }))
    setErrors((e) => ({ ...e, [key]: undefined }))
  }

  // Move focus to the step heading after advancing. Without this the DOM
  // changes and a screen reader says nothing.
  React.useEffect(() => {
    if (step > 0) headingRef.current?.focus()
  }, [step])

  function next() {
    const found = validateStep(step, values)
    if (Object.keys(found).length > 0) {
      setErrors(found)
      return
    }
    setStep((s) => Math.min(s + 1, steps.length - 1))
  }

  async function handleSubmit(event: React.FormEvent<HTMLFormElement>) {
    event.preventDefault()
    const found = validateStep(step, values)
    if (Object.keys(found).length > 0) {
      setErrors(found)
      return
    }
    await (onSubmit?.(values) ?? Promise.resolve())
    setDone(true)
  }

  if (done) {
    return (
      <section className={`mx-auto w-full max-w-2xl px-4 py-16 sm:px-6 ${className}`}>
        <div className="flex flex-col items-center rounded-2xl border border-emerald-500/30 bg-emerald-500/5 p-12 text-center">
          <span className="flex h-12 w-12 items-center justify-center rounded-full bg-emerald-500/15 text-emerald-600 dark:text-emerald-400">
            <Check aria-hidden className="h-6 w-6" />
          </span>
          <p className="mt-4 font-semibold">{successMessage}</p>
        </div>
      </section>
    )
  }

  const isLast = step === steps.length - 1

  return (
    <section className={`mx-auto w-full max-w-2xl px-4 py-16 sm:px-6 ${className}`}>
      <h2 className="text-center text-2xl font-bold tracking-tight sm:text-3xl">{heading}</h2>

      {/* -- Stepper --------------------------------------------------- */}
      <ol className="mt-8 flex items-center gap-2">
        {steps.map((label, i) => {
          const state = i < step ? 'complete' : i === step ? 'current' : 'upcoming'
          return (
            <li key={label} className="flex min-w-0 flex-1 items-center gap-2">
              <span
                aria-current={state === 'current' ? 'step' : undefined}
                className={`flex h-8 w-8 shrink-0 items-center justify-center rounded-full border text-xs font-bold ${
                  state === 'complete'
                    ? 'border-primary bg-primary text-primary-foreground'
                    : state === 'current'
                      ? 'border-primary text-primary'
                      : 'border-border/60 text-muted-foreground'
                }`}
              >
                {state === 'complete' ? <Check aria-hidden className="h-4 w-4" /> : i + 1}
                {state === 'complete' ? <span className="sr-only">completed</span> : null}
              </span>
              <span
                className={`hidden min-w-0 truncate text-xs font-medium sm:block ${
                  state === 'upcoming' ? 'text-muted-foreground' : 'text-foreground'
                }`}
              >
                {label}
              </span>
              {i < steps.length - 1 ? (
                <span
                  aria-hidden
                  className={`h-px flex-1 ${i < step ? 'bg-primary' : 'bg-border'}`}
                />
              ) : null}
            </li>
          )
        })}
      </ol>

      <form
        onSubmit={handleSubmit}
        className="mt-8 rounded-2xl border border-border/60 bg-card/40 p-6 sm:p-8"
      >
        {steps[step] ? (
          <h3
            ref={headingRef}
            tabIndex={-1}
            data-stress-ignore
            className="text-lg font-semibold outline-none"
          >
            {steps[step]}
          </h3>
        ) : null}

        <div className="mt-5 space-y-4">
          {step === 0 ? (
            <>
              <TextField
                id={`${uid}-ms-name`}
                label="Full name"
                autoComplete="name"
                value={values.name}
                error={errors.name}
                onChange={(v) => set('name', v)}
              />
              <TextField
                id={`${uid}-ms-email`}
                label="Work email"
                type="email"
                autoComplete="email"
                value={values.email}
                error={errors.email}
                onChange={(v) => set('email', v)}
              />
            </>
          ) : null}

          {step === 1 ? (
            <>
              <TextField
                id={`${uid}-ms-company`}
                label="Company"
                autoComplete="organization"
                value={values.company}
                error={errors.company}
                onChange={(v) => set('company', v)}
              />
              <div>
                <label htmlFor={`${uid}-ms-size`} className="block text-sm font-medium">
                  Team size
                </label>
                <select
                  id={`${uid}-ms-size`}
                  value={values.teamSize}
                  onChange={(e) => set('teamSize', e.target.value)}
                  className="mt-1.5 h-11 w-full rounded-xl border border-border/60 bg-background/60 px-3 text-sm focus:border-primary/50 focus:outline-none focus:ring-2 focus:ring-ring/30"
                >
                  {['1–10', '11–50', '51–200', '200+'].map((size) => (
                    <option key={size}>{size}</option>
                  ))}
                </select>
              </div>
            </>
          ) : null}

          {step === 2 ? (
            <>
              <div>
                <label htmlFor={`${uid}-ms-usecase`} className="block text-sm font-medium">
                  What will you use this for?
                </label>
                <textarea
                  id={`${uid}-ms-usecase`}
                  rows={4}
                  value={values.useCase}
                  aria-invalid={errors.useCase ? true : undefined}
                  aria-describedby={errors.useCase ? 'ms-usecase-error' : undefined}
                  onChange={(e) => set('useCase', e.target.value)}
                  className={`mt-1.5 w-full resize-y rounded-xl border bg-background/60 px-3 py-2.5 text-sm focus:outline-none focus:ring-2 focus:ring-ring/30 ${
                    errors.useCase ? 'border-destructive' : 'border-border/60 focus:border-primary/50'
                  }`}
                />
                {errors.useCase ? (
                  <p id={`${uid}-ms-usecase-error`} className="mt-1.5 text-xs text-destructive">
                    {errors.useCase}
                  </p>
                ) : null}
              </div>
              <TextField
                id={`${uid}-ms-referral`}
                label="How did you hear about us?"
                optional
                value={values.referral}
                onChange={(v) => set('referral', v)}
              />
            </>
          ) : null}
        </div>

        <div className="mt-7 flex items-center justify-between gap-3">
          <button
            type="button"
            onClick={() => setStep((s) => Math.max(0, s - 1))}
            disabled={step === 0}
            className="inline-flex h-11 items-center gap-1 rounded-xl border border-border/60 px-4 text-sm font-semibold transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40"
          >
            <ChevronLeft aria-hidden className="h-4 w-4 rtl:rotate-180" />
            Back
          </button>

          {isLast ? (
            <button
              type="submit"
              className="inline-flex h-11 items-center rounded-xl bg-primary px-6 text-sm font-semibold text-primary-foreground transition-opacity hover:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
            >
              {submitLabel}
            </button>
          ) : (
            <button
              type="button"
              onClick={next}
              className="inline-flex h-11 items-center gap-1 rounded-xl bg-primary px-6 text-sm font-semibold text-primary-foreground transition-opacity hover:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
            >
              Continue
              <ChevronRight aria-hidden className="h-4 w-4 rtl:rotate-180" />
            </button>
          )}
        </div>
      </form>
    </section>
  )
}

/** Text input wired to an error message via aria-describedby. */
function TextField({
  id,
  label,
  value,
  onChange,
  error,
  type = 'text',
  autoComplete,
  optional = false,
}: {
  id: string
  label: string
  value: string
  onChange: (value: string) => void
  error?: string
  type?: string
  autoComplete?: string
  optional?: boolean
}) {
  const errorId = `${id}-error`
  return (
    <div>
      <label htmlFor={id} className="block text-sm font-medium">
        {label}
        {optional ? (
          <span className="ms-1 text-xs font-normal text-muted-foreground">(optional)</span>
        ) : null}
      </label>
      <input
        id={id}
        type={type}
        autoComplete={autoComplete}
        value={value}
        aria-invalid={error ? true : undefined}
        aria-describedby={error ? errorId : undefined}
        onChange={(e) => onChange(e.target.value)}
        className={`mt-1.5 h-11 w-full rounded-xl border bg-background/60 px-3 text-sm focus:outline-none focus:ring-2 focus:ring-ring/30 ${
          error ? 'border-destructive' : 'border-border/60 focus:border-primary/50'
        }`}
      />
      {error ? (
        <p id={errorId} className="mt-1.5 text-xs text-destructive">
          {error}
        </p>
      ) : null}
    </div>
  )
}

Before you paste

  • Styling is Tailwind utility classes on semantic tokens (bg-card, text-muted-foreground) — it inherits your theme instead of overriding it.
  • Install: npm i lucide-react
  • Every prop has a default, so it renders standalone before you wire it up.

Where it goes

Drop it at components/multi-step-form.tsx and import it where you need the section:

import { MultiStepForm } from '@/components/multi-step-form'

Customize

3 of this block’s props are simple enough to drive from here. Change them and the block below re-renders — it is the same component whose source is above, not a mock of it. Everything else it accepts is in the table underneath.

Props

Read out of the component’s own type and signature, so this cannot drift from the source below. Every prop has a default — the component renders standalone before you pass it anything.

PropTypeDefault
headingstring'Set up your workspace'
stepsstring[]DEFAULT_STEPS
submitLabelstring'Create workspace'
successMessagestring'Workspace created. Check your email for the …
onSubmit(values: MultiStepValues) => void | Promise<void>—
classNamestring''

Not using React?

The same block rendered once to markup, wrapped as a file your framework compiles. Tailwind classes are framework-agnostic, so the design transfers intact — the behaviour does not.

This block is interactive. The markup below is its initial state with the event handlers stripped — you will need to re-wire the behaviour in your framework.

multi-step-form.html
<!--
  Multi-Step Form with Validation — markup from the Hoverlab catalog.

  This is the block rendered once to HTML and wrapped as a component
  file. It is not a port of the React source: the Tailwind classes carry
  the design, which is the part that took the work, and they are the same
  in every framework.

  This block is interactive in React and the handlers are NOT here.
  Buttons, toggles and menus render in their initial state and do
  nothing until you wire them up.
-->
<section class="mx-auto w-full max-w-2xl px-4 py-16 sm:px-6 ">
  <h2 class="text-center text-2xl font-bold tracking-tight sm:text-3xl">Set up your workspace</h2>
  <ol class="mt-8 flex items-center gap-2">
    <li class="flex min-w-0 flex-1 items-center gap-2">
      <span aria-current="step" class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full border text-xs font-bold border-primary text-primary">1</span>
      <span class="hidden min-w-0 truncate text-xs font-medium sm:block text-foreground">Your details</span>
      <span aria-hidden="true" class="h-px flex-1 bg-border"></span>
    </li>
    <li class="flex min-w-0 flex-1 items-center gap-2">
      <span class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full border text-xs font-bold border-border/60 text-muted-foreground">2</span>
      <span class="hidden min-w-0 truncate text-xs font-medium sm:block text-muted-foreground">Your team</span>
      <span aria-hidden="true" class="h-px flex-1 bg-border"></span>
    </li>
    <li class="flex min-w-0 flex-1 items-center gap-2">
      <span class="flex h-8 w-8 shrink-0 items-center justify-center rounded-full border text-xs font-bold border-border/60 text-muted-foreground">3</span>
      <span class="hidden min-w-0 truncate text-xs font-medium sm:block text-muted-foreground">Finish</span>
    </li>
  </ol>
  <form class="mt-8 rounded-2xl border border-border/60 bg-card/40 p-6 sm:p-8">
    <h3 tabindex="-1" data-stress-ignore="true" class="text-lg font-semibold outline-none">Your details</h3>
    <div class="mt-5 space-y-4">
      <div>
        <label for="_R_0_-ms-name" class="block text-sm font-medium">Full name</label>
        <input id="_R_0_-ms-name" type="text" autoComplete="name" class="mt-1.5 h-11 w-full rounded-xl border bg-background/60 px-3 text-sm focus:outline-none focus:ring-2 focus:ring-ring/30 border-border/60 focus:border-primary/50" value="" />
      </div>
      <div>
        <label for="_R_0_-ms-email" class="block text-sm font-medium">Work email</label>
        <input id="_R_0_-ms-email" type="email" autoComplete="email" class="mt-1.5 h-11 w-full rounded-xl border bg-background/60 px-3 text-sm focus:outline-none focus:ring-2 focus:ring-ring/30 border-border/60 focus:border-primary/50" value="" />
      </div>
    </div>
    <div class="mt-7 flex items-center justify-between gap-3">
      <button type="button" disabled="" class="inline-flex h-11 items-center gap-1 rounded-xl border border-border/60 px-4 text-sm font-semibold transition-colors hover:bg-muted focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-40"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevron-left h-4 w-4 rtl:rotate-180" aria-hidden="true"><path d="m15 18-6-6 6-6"></path></svg>Back</button>
      <button type="button" class="inline-flex h-11 items-center gap-1 rounded-xl bg-primary px-6 text-sm font-semibold text-primary-foreground transition-opacity hover:opacity-90 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background">Continue<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevron-right h-4 w-4 rtl:rotate-180" aria-hidden="true"><path d="m9 18 6-6-6-6"></path></svg></button>
    </div>
  </form>
</section>
  • This is rendered HTML, not a translation of the React source. The Tailwind classes carry the design and work in any framework.
  • It is one frame: the component in its initial state, with no props applied beyond the defaults.
  • This block is interactive in React — toggles, menus or form state. None of that survives here; the markup is the closed/default state and the handlers are gone. Re-wire them in your own framework.
  • Requires Tailwind, and the design tokens the classes reference (bg-card, text-muted-foreground, and so on). The template ZIPs ship a globals.css that defines them.

What each framework gets across the whole catalog — effects convert properly; this rung is markup.

For AI

The component, its props, the design tokens it expects and the command that installs it — as one prompt. Paste it into Claude, Cursor, v0 or ChatGPT and what they build around it will match the rest of the catalog instead of inventing its own system.

See the prompt

Used in these pages

Want the whole screen instead of this one section? Open a page and copy it entire.

5 more blocks in Contact & Forms

All of them free to read, copy and install — no account, no locked tiles, no watermarked preview. The whole catalog is open, and so are the API and the CLI.

Browse Contact & Forms

Shipping one commercially

Copying the code is free. Putting it in client work or a paid product is what Pro is for — the licence, not the access.

  • A commercial licence for everything in the catalog
  • Unlimited bundle exports, in Vue, Svelte and Tailwind
  • One payment — no subscription, nothing to renew
Pro — $79 once

More Contact & Forms blocks

View category
Open the full page for this block

Split Contact Form

A contact form beside the channels that bypass it — a real address, a support link and a response-time promise, which is what makes a form people cannot see into feel worth filling.

Contact & Forms279 lines1 dep
Open the full page for this block

Inline Feedback Widget

One click to rate, everything after it optional — the shape that collects a complaint from someone mid-task who would never open a contact page.

Contact & Forms248 lines1 dep
Open the full page for this block

Form with Error Summary

The state every form reaches and none of them illustrate: a focused summary at the top linking to each bad field, validation that waits for submit, and somewhere for the failure that belongs to no field.

Contact & Forms320 lines1 dep
Open the full page for this block

Contact Sales Form

A qualifying contact form that asks the three things a first reply needs, and says what happens next before you send it.

Contact & Forms175 linesNo deps
Open the full page for this block

Support Ticket Form

A support form that asks for the one thing that halves resolution time — what you already tried — and says when a human will read it.

Contact & Forms169 linesNo deps