Skip to content
Marketing 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.

320 lineslucide-reactAdded 27 Aug 2026
  • form
  • validation
  • errors
  • accessibility
  • summary

What's included

  • components/form-error-summary.tsx
  • Needs lucide-react

Works with

  • React
  • Next.js
  • Tailwind CSS
  • TypeScript

npx hoverlab add form-error-summary

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

Create a team account

We use this for the account, and nothing else.

Error: Enter an email address in the format name@example.com.

Error: Enter the company this is for.

A number between 1 and 500. You can change it later.

Error: Seats must be a whole number between 1 and 500.

At least 12 characters. Length is the only requirement.

Error: Use at least 12 characters.

Nothing is checked until you submit — you will not be told your email is wrong while you are still typing it.

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

Source

components/form-error-summary.tsx
'use client'

/**
 * <FormErrorSummary> — the form after it has been rejected.
 *
 * Contact & Forms had the split contact form, the multi-step flow, the
 * feedback widget and the scheduler: four forms drawn in the state where
 * everything is fine. This is the fifth state all of them eventually
 * reach and none of them illustrate, and it is the state where a form
 * either recovers a submission or loses it.
 *
 * THE ONE THING THIS GETS RIGHT THAT MOST DO NOT
 *
 * There is a summary at the top, it is focused on submit, and every line
 * in it is a link to the field it is about. On a long form the errors are
 * usually below the fold; a red border on a control nobody can see is not
 * a message. This is the pattern the UK Government Digital Service and the
 * WCAG error-identification criteria both land on, and it is close to
 * unheard-of outside government work.
 *
 * ERRORS APPEAR ON SUBMIT, THEN TRACK THE FIELD
 *
 * Validating every keystroke means telling somebody their email is invalid
 * while they are typing the second letter of it, which is both wrong and
 * rude. Nothing is marked until submit. After that, a field that has been
 * marked revalidates as it changes, so the fix is confirmed immediately
 * and the summary shrinks as they go.
 *
 * THE MESSAGE SAYS HOW TO FIX IT
 *
 * "Enter an email address in the format name@example.com", not "invalid".
 * The rule is stated before it is broken as well — the password hint is
 * always visible, not revealed as a punishment.
 *
 * FAILURES THAT BELONG TO NO FIELD HAVE A HOME
 *
 * A declined card, a duplicate account, a service that was down: real
 * submissions fail for reasons no field can own. They render in the same
 * summary rather than as a toast that disappears before it is read, and
 * the form keeps every value the person entered.
 *
 * ACCESSIBILITY: the summary is `role="alert"` and `tabIndex={-1}` so it
 * can take focus, each field carries `aria-invalid` and `aria-describedby`
 * pointing at both its hint and its error, and every message is prefixed
 * with a visible "Error:" so the failure is not carried by colour alone.
 */

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

export interface FormErrorSummaryProps {
  /** Set to see the summary handle a failure that belongs to no field. */
  simulateServerError?: boolean
  /**
   * Opens already rejected, because that is the state this block is for.
   * Pass `false` for a clean form — the transition from clean to rejected
   * is the same code path either way.
   */
  startRejected?: boolean
  className?: string
}

/* Two plausible mistakes and three blanks — a realistic first submission. */
const REJECTED_VALUES: Record<string, string> = {
  'full-name': 'Sam Keller',
  'work-email': 'sam.keller@northwind',
  company: '',
  seats: '2,000',
  password: 'hunter2',
}

interface FieldDef {
  id: string
  label: string
  type: string
  hint?: string
  autoComplete?: string
  validate: (value: string) => string | null
}

const FIELDS: FieldDef[] = [
  {
    id: 'full-name',
    label: 'Full name',
    type: 'text',
    autoComplete: 'name',
    validate: (v) => (v.trim() ? null : 'Enter your full name.'),
  },
  {
    id: 'work-email',
    label: 'Work email',
    type: 'email',
    autoComplete: 'email',
    hint: 'We use this for the account, and nothing else.',
    validate: (v) =>
      /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v.trim())
        ? null
        : 'Enter an email address in the format name@example.com.',
  },
  {
    id: 'company',
    label: 'Company',
    type: 'text',
    autoComplete: 'organization',
    validate: (v) => (v.trim() ? null : 'Enter the company this is for.'),
  },
  {
    id: 'seats',
    label: 'Number of seats',
    type: 'text',
    hint: 'A number between 1 and 500. You can change it later.',
    validate: (v) => {
      const n = Number(v.trim())
      if (!v.trim()) return 'Enter how many seats you need.'
      if (!Number.isInteger(n) || n < 1 || n > 500)
        return 'Seats must be a whole number between 1 and 500.'
      return null
    },
  },
  {
    id: 'password',
    label: 'Password',
    type: 'password',
    autoComplete: 'new-password',
    /* The rule is visible before it is broken, not after. */
    hint: 'At least 12 characters. Length is the only requirement.',
    validate: (v) => (v.length >= 12 ? null : 'Use at least 12 characters.'),
  },
]

export function FormErrorSummary({
  simulateServerError = true,
  startRejected = true,
  className = '',
}: FormErrorSummaryProps) {
  const [values, setValues] = React.useState<Record<string, string>>(() =>
    Object.fromEntries(
      FIELDS.map((f) => [f.id, startRejected ? (REJECTED_VALUES[f.id] ?? '') : '']),
    ),
  )
  const [errors, setErrors] = React.useState<Record<string, string>>(() => {
    if (!startRejected) return {}
    const found: Record<string, string> = {}
    for (const field of FIELDS) {
      const message = field.validate(REJECTED_VALUES[field.id] ?? '')
      if (message) found[field.id] = message
    }
    return found
  })
  const [formError, setFormError] = React.useState<string | null>(null)
  const [submitted, setSubmitted] = React.useState(startRejected)
  const [done, setDone] = React.useState(false)
  const summary = React.useRef<HTMLDivElement>(null)

  const setValue = (id: string, value: string) => {
    setValues((v) => ({ ...v, [id]: value }))
    /* Only revalidate a field that has already been marked. */
    if (submitted && errors[id] !== undefined) {
      const field = FIELDS.find((f) => f.id === id)
      const message = field?.validate(value) ?? null
      setErrors(({ [id]: _drop, ...rest }) => (message ? { ...rest, [id]: message } : rest))
    }
  }

  const onSubmit = (event: React.FormEvent) => {
    event.preventDefault()
    setSubmitted(true)
    const found: Record<string, string> = {}
    for (const field of FIELDS) {
      const message = field.validate(values[field.id] ?? '')
      if (message) found[field.id] = message
    }
    setErrors(found)

    const serverSide =
      Object.keys(found).length === 0 && simulateServerError && !done
        ? 'That email is already on an account for this company. Sign in instead, or use a different address.'
        : null
    setFormError(serverSide)

    if (Object.keys(found).length === 0 && !serverSide) {
      setDone(true)
      return
    }
    /* Focus the summary — the errors are usually below the fold. */
    window.requestAnimationFrame(() => summary.current?.focus())
  }

  const listed = FIELDS.filter((f) => errors[f.id])
  const showSummary = submitted && (listed.length > 0 || formError)

  if (done) {
    return (
      <section className={`mx-auto w-full max-w-lg px-4 py-16 sm:px-6 ${className}`}>
        <div className="rounded-2xl border border-border bg-card p-6 text-center">
          <span
            aria-hidden
            className="mx-auto flex h-10 w-10 items-center justify-center rounded-full bg-emerald-500/10 text-emerald-600 dark:text-emerald-400"
          >
            <Check className="h-5 w-5" />
          </span>
          <h2 className="mt-3 text-lg font-semibold text-foreground">Account created</h2>
          <p className="mt-1 text-sm text-muted-foreground">
            Nothing you typed was lost on the way here.
          </p>
        </div>
      </section>
    )
  }

  return (
    <section className={`mx-auto w-full max-w-lg px-4 py-16 sm:px-6 ${className}`}>
      <form
        noValidate
        onSubmit={onSubmit}
        className="rounded-2xl border border-border bg-card p-6 sm:p-8"
      >
        <h2 className="text-xl font-semibold tracking-tight text-foreground">
          Create a team account
        </h2>

        {showSummary ? (
          <div
            ref={summary}
            role="alert"
            tabIndex={-1}
            className="mt-5 rounded-xl border border-destructive/40 bg-destructive/5 p-4 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background"
          >
            <h3 className="flex items-center gap-2 text-sm font-semibold text-foreground">
              <AlertCircle aria-hidden className="h-4 w-4 text-destructive" />
              {listed.length > 0
                ? `There ${listed.length === 1 ? 'is 1 problem' : `are ${listed.length} problems`} with this form`
                : 'This could not be submitted'}
            </h3>

            {listed.length > 0 ? (
              <ul className="mt-2 space-y-1">
                {listed.map((f) => (
                  <li key={f.id}>
                    {/* Each line goes to the field it is about. */}
                    <a
                      href={`#${f.id}`}
                      onClick={(event) => {
                        event.preventDefault()
                        document.getElementById(f.id)?.focus()
                      }}
                      className="rounded text-sm text-destructive underline underline-offset-4 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"
                    >
                      {f.label}: {errors[f.id]}
                    </a>
                  </li>
                ))}
              </ul>
            ) : null}

            {/* The failure that belongs to no field. */}
            {formError ? (
              <p className="mt-2 text-sm text-foreground">{formError}</p>
            ) : null}
          </div>
        ) : null}

        <div className="mt-6 space-y-5">
          {FIELDS.map((field) => {
            const error = errors[field.id]
            const hintId = field.hint ? `${field.id}-hint` : undefined
            const errorId = error ? `${field.id}-error` : undefined
            return (
              <div key={field.id}>
                <label
                  htmlFor={field.id}
                  className="block text-sm font-medium text-foreground"
                >
                  {field.label}
                </label>
                {field.hint ? (
                  <p id={hintId} className="mt-0.5 text-xs text-muted-foreground">
                    {field.hint}
                  </p>
                ) : null}
                <input
                  id={field.id}
                  name={field.id}
                  type={field.type}
                  autoComplete={field.autoComplete}
                  value={values[field.id] ?? ''}
                  onChange={(event) => setValue(field.id, event.target.value)}
                  aria-invalid={error ? true : undefined}
                  aria-describedby={[hintId, errorId].filter(Boolean).join(' ') || undefined}
                  className={`mt-1.5 h-10 w-full rounded-lg border bg-background px-3 text-sm text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background ${
                    error ? 'border-destructive' : 'border-field'
                  }`}
                />
                {error ? (
                  /* "Error:" in text — the state is not carried by colour. */
                  <p id={errorId} className="mt-1.5 text-sm text-destructive">
                    <span className="font-semibold">Error:</span> {error}
                  </p>
                ) : null}
              </div>
            )
          })}
        </div>

        <button
          type="submit"
          className="mt-6 inline-flex h-10 w-full items-center justify-center rounded-lg bg-primary px-4 text-sm font-semibold text-primary-foreground transition 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"
        >
          Create account
        </button>

        <p className="mt-3 text-xs text-muted-foreground">
          Nothing is checked until you submit — you will not be told your email
          is wrong while you are still typing it.
        </p>
      </form>
    </section>
  )
}

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/form-error-summary.tsx and import it where you need the section:

import { FormErrorSummary } from '@/components/form-error-summary'

Customize

2 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
simulateServerErrorSet to see the summary handle a failure that belongs to no field.booleantrue
startRejectedOpens already rejected, because that is the state this block is for. Pass `false` for a clean form — the transition from clean to rejected is the same code path either way.booleantrue
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.

form-error-summary.html
<!--
  Form with Error Summary — 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-lg px-4 py-16 sm:px-6 ">
  <form noValidate="" class="rounded-2xl border border-border bg-card p-6 sm:p-8">
    <h2 class="text-xl font-semibold tracking-tight text-foreground">Create a team account</h2>
    <div role="alert" tabindex="-1" class="mt-5 rounded-xl border border-destructive/40 bg-destructive/5 p-4 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background">
      <h3 class="flex items-center gap-2 text-sm font-semibold text-foreground"><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-circle-alert h-4 w-4 text-destructive" aria-hidden="true"><circle cx="12" cy="12" r="10"></circle><line x1="12" x2="12" y1="8" y2="12"></line><line x1="12" x2="12.01" y1="16" y2="16"></line></svg>There are 4 problems with this form</h3>
      <ul class="mt-2 space-y-1">
        <li>
          <a href="#work-email" class="rounded text-sm text-destructive underline underline-offset-4 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">Work email: Enter an email address in the format name@example.com.</a>
        </li>
        <li>
          <a href="#company" class="rounded text-sm text-destructive underline underline-offset-4 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">Company: Enter the company this is for.</a>
        </li>
        <li>
          <a href="#seats" class="rounded text-sm text-destructive underline underline-offset-4 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">Number of seats: Seats must be a whole number between 1 and 500.</a>
        </li>
        <li>
          <a href="#password" class="rounded text-sm text-destructive underline underline-offset-4 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring">Password: Use at least 12 characters.</a>
        </li>
      </ul>
    </div>
    <div class="mt-6 space-y-5">
      <div>
        <label for="full-name" class="block text-sm font-medium text-foreground">Full name</label>
        <input id="full-name" type="text" autoComplete="name" class="mt-1.5 h-10 w-full rounded-lg border bg-background px-3 text-sm text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background border-field" name="full-name" value="Sam Keller" />
      </div>
      <div>
        <label for="work-email" class="block text-sm font-medium text-foreground">Work email</label>
        <p id="work-email-hint" class="mt-0.5 text-xs text-muted-foreground">We use this for the account, and nothing else.</p>
        <input id="work-email" type="email" autoComplete="email" aria-invalid="true" aria-describedby="work-email-hint work-email-error" class="mt-1.5 h-10 w-full rounded-lg border bg-background px-3 text-sm text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background border-destructive" name="work-email" value="sam.keller@northwind" />
        <p id="work-email-error" class="mt-1.5 text-sm text-destructive"><span class="font-semibold">Error:</span> Enter an email address in the format name@example.com.</p>
      </div>
      <div>
        <label for="company" class="block text-sm font-medium text-foreground">Company</label>
        <input id="company" type="text" autoComplete="organization" aria-invalid="true" aria-describedby="company-error" class="mt-1.5 h-10 w-full rounded-lg border bg-background px-3 text-sm text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background border-destructive" name="company" value="" />
        <p id="company-error" class="mt-1.5 text-sm text-destructive"><span class="font-semibold">Error:</span> Enter the company this is for.</p>
      </div>
      <div>
        <label for="seats" class="block text-sm font-medium text-foreground">Number of seats</label>
        <p id="seats-hint" class="mt-0.5 text-xs text-muted-foreground">A number between 1 and 500. You can change it later.</p>
        <input id="seats" type="text" aria-invalid="true" aria-describedby="seats-hint seats-error" class="mt-1.5 h-10 w-full rounded-lg border bg-background px-3 text-sm text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background border-destructive" name="seats" value="2,000" />
        <p id="seats-error" class="mt-1.5 text-sm text-destructive"><span class="font-semibold">Error:</span> Seats must be a whole number between 1 and 500.</p>
      </div>
      <div>
        <label for="password" class="block text-sm font-medium text-foreground">Password</label>
        <p id="password-hint" class="mt-0.5 text-xs text-muted-foreground">At least 12 characters. Length is the only requirement.</p>
        <input id="password" type="password" autoComplete="new-password" aria-invalid="true" aria-describedby="password-hint password-error" class="mt-1.5 h-10 w-full rounded-lg border bg-background px-3 text-sm text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background border-destructive" name="password" value="hunter2" />
        <p id="password-error" class="mt-1.5 text-sm text-destructive"><span class="font-semibold">Error:</span> Use at least 12 characters.</p>
      </div>
    </div>
    <button type="submit" class="mt-6 inline-flex h-10 w-full items-center justify-center rounded-lg bg-primary px-4 text-sm font-semibold text-primary-foreground transition 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">Create account</button>
    <p class="mt-3 text-xs text-muted-foreground">Nothing is checked until you submit — you will not be told your email is wrong while you are still typing it.</p>
  </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

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.

Contact & Forms373 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

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