# Form

A form wrapper that simplifies validation and submission.

- Category: Forms
- Page: https://wunderui.com/components/form
- Tier: Free

## Install

```bash
npx wunderui-cli add form
```

## Import

```tsx
import { Form } from "@/components/ui/form"
```

## Minimal usage

Then use it:

```tsx
import { Button } from "@/components/ui/button"
import { Field, FieldError, FieldLabel } from "@/components/ui/field"
import { Form } from "@/components/ui/form"
import { Input } from "@/components/ui/input"

export function Subscribe() {
  return (
    <Form onFormSubmit={(values) => console.log(values)}>
      <Field name="email">
        <FieldLabel>Work email</FieldLabel>
        <Input type="email" required placeholder="name@company.com" />
        <FieldError match="valueMissing">Enter your work email address.</FieldError>
        <FieldError match="typeMismatch">Enter an email address like name@company.com.</FieldError>
      </Field>
      <Button type="submit" variant="gradient">
        Subscribe
      </Button>
    </Form>
  )
}
```

Expected result: You see a label, a white field and a Subscribe button. With the field empty, pressing it turns the field red and shows its message; with an address, the form sends.

## Usage

```tsx
import { useState } from "react"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import { Button } from "@/components/ui/button"
import { Field, FieldDescription, FieldError, FieldLabel } from "@/components/ui/field"
import { Form } from "@/components/ui/form"
import { FormActions } from "@/components/ui/form-actions"
import { Input } from "@/components/ui/input"
import { Spinner } from "@/components/ui/spinner"

type Values = { name: string; email: string; size: string }
type Errors = Record<string, string>
type Phase = "idle" | "validating" | "submitting" | "success" | "failed"

const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
const LABELS = { name: "Full name", email: "Work email", size: "Team size" } as const
const FIELDS = [
  { key: "name", label: "Full name", hint: "As shown on your invoices.", autoComplete: "name", inputMode: "text" },
  { key: "email", label: "Work email", hint: "We send receipts to this address.", autoComplete: "email", inputMode: "email" },
  { key: "size", label: "Team size", hint: "Between 1 and 50 people.", autoComplete: "off", inputMode: "numeric" },
] as const

function validate(values: Values): Errors {
  const errors: Errors = {}
  if (!values.name.trim()) errors.name = "Enter your full name."
  if (!EMAIL.test(values.email)) errors.email = "Enter a work email address, like name@company.com."
  const size = Number(values.size)
  if (!Number.isInteger(size) || size < 1 || size > 50) errors.size = "Enter a number between 1 and 50."
  return errors
}

export function Example() {
  const [saved, setSaved] = useState<Values>({ name: "Nora Lindgren", email: "info@wunderui.com", size: "12" })
  const [values, setValues] = useState<Values>({ name: "Nora Lindgren", email: "info@wunderui.com", size: "12" })
  const [errors, setErrors] = useState<Errors>({})
  const [phase, setPhase] = useState<Phase>("idle")

  const issues = (Object.keys(LABELS) as (keyof Values)[]).filter((key) => errors[key])
  const dirty = (Object.keys(LABELS) as (keyof Values)[]).some((key) => values[key] !== saved[key])

  function focusField(from: Element, key: keyof Values) {
    from.closest("form")?.querySelector<HTMLElement>(`[name="${key}"]`)?.focus()
  }

  function change(key: keyof Values, value: string) {
    setValues((current) => ({ ...current, [key]: value }))
    setErrors((current) => Object.fromEntries(Object.entries(current).filter(([name]) => name !== key)))
    if (phase === "success" || phase === "failed") setPhase("idle")
  }

  function submit(_values: unknown, details: { event: Event }) {
    const next = validate(values)
    setErrors(next)
    const first = (Object.keys(LABELS) as (keyof Values)[]).find((key) => next[key])
    if (first) {
      const target = details.event.target as Element
      window.requestAnimationFrame(() => focusField(target, first))
      return
    }
    setPhase("submitting")
    window.setTimeout(() => {
      setSaved(values)
      setPhase("success")
    }, 1200)
  }

  return (
    <Form errors={errors} onFormSubmit={submit} className="gap-4">
      <div>
        <h3 className="text-sm font-semibold text-foreground">Profile</h3>
        <p className="text-sm text-text-secondary">Basic details your team sees on shared projects.</p>
      </div>
        {issues.length > 0 && (
          <Alert variant="negative">
            <AlertTitle>
              Fix {issues.length} {issues.length === 1 ? "field" : "fields"} to continue
            </AlertTitle>
            <AlertDescription>Select an item to jump to the field.</AlertDescription>
            <ul className="flex flex-col gap-1 text-sm">
              {issues.map((key) => (
                <li key={key}>
                  <button type="button" onClick={(event) => focusField(event.currentTarget, key)} className="text-left underline underline-offset-2">
                    {LABELS[key]}: {errors[key]}
                  </button>
                </li>
              ))}
            </ul>
          </Alert>
        )}
      {phase === "success" && (
        <Alert variant="positive">
          <AlertTitle>Profile saved</AlertTitle>
          <AlertDescription>Your changes are live for the whole team.</AlertDescription>
        </Alert>
      )}
      {phase === "failed" && (
        <Alert variant="negative">
          <AlertTitle>We couldn't save your changes</AlertTitle>
          <AlertDescription>Your entries are kept. Check your connection and try again.</AlertDescription>
        </Alert>
      )}
            {FIELDS.map((field) => (
              <Field key={field.key} name={field.key}>
                <FieldLabel>
                  {field.label} <span className="ml-2 text-xs font-normal text-text-tertiary">Required</span>
                </FieldLabel>
                <Input
                  value={values[field.key]}
                  onChange={(event) => change(field.key, event.target.value)}
                  inputMode={field.inputMode}
                  autoComplete={field.autoComplete}
                />
                <FieldDescription>{field.hint}</FieldDescription>
                <FieldError>{errors[field.key]}</FieldError>
              </Field>
            ))}
      <p aria-live="polite" className="flex min-h-5 items-center gap-2 text-xs text-text-secondary">
        {phase === "validating" || phase === "submitting" ? <Spinner className="text-current" /> : null}
        {phase === "validating" && "Checking your entries…"}
        {phase === "submitting" && "Saving…"}
        {phase === "success" && !dirty && "All changes saved"}
        {phase === "idle" && dirty && issues.length === 0 && "You have unsaved changes"}
      </p>
      <FormActions>
        <Button
          type="button"
          variant="plain"
          disabled={phase === "submitting"}
          onClick={() => {
            setValues(saved)
            setErrors({})
            setPhase("idle")
          }}
        >
          Cancel
        </Button>
        <Button type="submit" variant="gradient" pending={phase === "submitting"} disabled={!dirty || phase === "validating"}>
          Save changes
        </Button>
      </FormActions>
    </Form>
  )
}
```

## When to use

### Use Form for

- A group of fields that are sent together, such as a profile, an address or a payment
- A form that has to check its fields, show what is wrong and say when it has saved
- A form whose rules only the server knows, such as a name that is already taken

### Use something else

- [Field](https://wunderui.com/components/field) for one labelled control with a helper and an error line, inside a form or on its own
- [Fieldset](https://wunderui.com/components/fieldset) for a group of related fields that share a legend, such as an address
- [Switch](https://wunderui.com/components/switch) for a setting that takes effect at once, without a save

## Keyboard

A form adds no keys of its own. Keyboard behaviour comes from the order of its controls and the browser's implicit submit.

| Key | Action |
|---|---|
| `Tab` or `Shift+Tab` | Moves through the fields and buttons in the order they are written. A disabled button is skipped; a pending button stays in the order. |
| `Enter` | In a text field, sends the form through its submit button. If a field is invalid, focus goes to the first one and its message shows. In a textarea it starts a new line. |
| `Space` or `Enter` | On a focused button, presses it. On the summary lines, moves focus to the field that is named. |

## Behavior

What the form does itself, and what it leaves to the page.

- **A native form:** Form renders a native form element, so action, method and onSubmit all work. It turns off the browser's own validation bubbles so fields show their own messages.
- **Submit:** The submit handler runs when every field is valid and gets an object with the value of each named field. It also stops the page from reloading, so name every Field: the name is the key.
- **When fields are checked:** Validation mode sets when fields are checked: on submit (default, then re-checks as the person types), on blur, or on every change. A Field can set its own mode.
- **Errors from outside:** Pass server errors as field names and messages, and the matching Field turns invalid and shows its message. Clear it when the person edits the field, or the red state stays.
- **Focus after a failed send:** After a failed send, focus moves to the first invalid field in page order, and that field is marked invalid. If you check fields yourself, move focus the same way.
- **Pending and success:** While the send runs, the main Button is pending: it keeps its place, shows a spinner and ignores presses, and the way out is disabled. When it ends, show the result in an Alert and the status line.
- **Pristine and unsaved:** A form with nothing to send, like a settings form without changes, may keep Save disabled. Once a field differs from what is saved, the status line says unsaved and Save is available.
- **Status messages:** The status line is a polite live region: changes are announced after the current speech and never take focus. The error summary is an alert and is announced at once.
- **Motion:** The form doesn't move. Field borders change colour quickly and the spinner in a pending button turns.
- **Reduced motion:** With reduced motion, border colours still change as a short fade and spinners stop turning. The pending label still says what is happening.

## Anatomy

- `Form`: A vertical stack with 20 px between children. It turns off browser validation bubbles, submits the named field values when all fields are valid, and focuses the first invalid one.
- `Error summary`: An Alert above the fields with the error count and one line per field that moves focus to it. Add it to long forms where an error can be out of sight; screen readers announce it.
- `Field`: One labelled control with its helper and error line. Its name joins it to the submitted values and to server errors; the error shows under the control and the helper line stays.
- `Status line`: One line of 12 px text above the actions that says what the form is doing: checking, saving, saved or unsaved. Screen readers announce changes politely, without taking focus.
- `FormActions`: The row of buttons at the end, built with FormActions. The submit button sends the form, and so does Enter in a text field.

## Best practices

### When to use

- Use a Form for everything a person sends together. A single field that acts at once, like a search box, needs no Form, and a setting that applies immediately is a Switch.

### Do

- Give every Field a name and handle the send in the submit handler. It gets the values by name and only runs when every field is valid, so Enter and the Save button take the same path.
- Say what to do in the message: Enter a work email address, like name@company.com, not Invalid input. Show it under the field and keep what the person typed.
- After a failed send, move focus to the first invalid field, and add an error summary to long forms. The summary jumps to each field and never replaces the message at the field.
- Show the work: a pending Save with its own label (Saving…), the way out disabled, and a confirmation when done. Say All changes saved in the status line, not only with colour.
- Keep the default: validate on submit, then re-check as the person corrects. Validate on blur for fields that are costly to get wrong, such as an address.

### Don't

- Don't disable the submit button to flag an invalid form, since it gives no reason. Let the person press it and tell them what is wrong; disable it only when there is nothing to send.
- Don't clear the fields after an error or a server failure. Name the problem, keep the entries and offer Try again.
- Don't run the check from a click handler on the submit button. Use the submit handler so keyboard and mouse users take the same path.

## API reference

### Form

| Prop | Type | Default | Description |
|---|---|---|---|
| actionsRef | React.RefObject<Form.Actions \| null> |  | A ref to imperative actions. `validate()` checks every field and `validate("name")` checks one, for example before the next step of a wizard. |
| className | string \| ((state: State) => string \| undefined) |  | Classes for the form. They replace the default stack (`flex flex-col gap-5`) where they conflict, so `gap-4` tightens it. It also takes a function of the form state. |
| errors | Record<string, string \| string[]> |  | Errors that come from outside, usually from a server after a send. The keys are Field names and the values are the message or messages. The Field with that name turns invalid and its `FieldError` shows the message. Clear it when the person edits the field. |
| onFormSubmit | (values, details) => void |  | Called with the values of the named fields when every field is valid. `values` is an object keyed by the `name` of each Field. It stops the page from reloading for you. `details.event` is the submit event. |
| render | React.ReactElement \| ComponentRenderFn<RenderFunctionProps, State> |  | Replaces the `<form>` element with another element or component, for example a framework's own form component. It also takes a function that returns the element. |
| style | React.CSSProperties \| ((state: State) => React.CSSProperties \| undefined) |  | Inline style for the form, or a function of the form state that returns one. |
| validationMode | "onBlur" \| "onChange" \| "onSubmit" | 'onSubmit' | When the fields are checked. `onSubmit` (the default) checks at the first send and re-checks as the person types afterwards, `onBlur` checks when a field loses focus and `onChange` checks on every change. The `validationMode` of a Field takes precedence. |

Also accepts React.FormHTMLAttributes attributes.

## Examples

### States: pristine, unsaved, validating, submitting, success, invalid and submit error

```tsx
import { useState } from "react"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import { Button } from "@/components/ui/button"
import { Field, FieldDescription, FieldError, FieldLabel } from "@/components/ui/field"
import { Form } from "@/components/ui/form"
import { FormActions } from "@/components/ui/form-actions"
import { Input } from "@/components/ui/input"
import { Spinner } from "@/components/ui/spinner"

type Values = { name: string; email: string; size: string }
type Errors = Record<string, string>
type Phase = "idle" | "validating" | "submitting" | "success" | "failed"

const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
const LABELS = { name: "Full name", email: "Work email", size: "Team size" } as const
const FIELDS = [
  { key: "name", label: "Full name", hint: "As shown on your invoices.", autoComplete: "name", inputMode: "text" },
  { key: "email", label: "Work email", hint: "We send receipts to this address.", autoComplete: "email", inputMode: "email" },
  { key: "size", label: "Team size", hint: "Between 1 and 50 people.", autoComplete: "off", inputMode: "numeric" },
] as const

function validate(values: Values): Errors {
  const errors: Errors = {}
  if (!values.name.trim()) errors.name = "Enter your full name."
  if (!EMAIL.test(values.email)) errors.email = "Enter a work email address, like name@company.com."
  const size = Number(values.size)
  if (!Number.isInteger(size) || size < 1 || size > 50) errors.size = "Enter a number between 1 and 50."
  return errors
}

export function Example() {
  const [saved, setSaved] = useState<Values>({ name: "Nora Lindgren", email: "info@wunderui.com", size: "12" })
  const [values, setValues] = useState<Values>({ name: "Nora Lindgren", email: "info@wunderui.com", size: "12" })
  const [errors, setErrors] = useState<Errors>({})
  const [phase, setPhase] = useState<Phase>("idle")

  const issues = (Object.keys(LABELS) as (keyof Values)[]).filter((key) => errors[key])
  const dirty = (Object.keys(LABELS) as (keyof Values)[]).some((key) => values[key] !== saved[key])

  function focusField(from: Element, key: keyof Values) {
    from.closest("form")?.querySelector<HTMLElement>(`[name="${key}"]`)?.focus()
  }

  function change(key: keyof Values, value: string) {
    setValues((current) => ({ ...current, [key]: value }))
    setErrors((current) => Object.fromEntries(Object.entries(current).filter(([name]) => name !== key)))
    if (phase === "success" || phase === "failed") setPhase("idle")
  }

  function submit(_values: unknown, details: { event: Event }) {
    const next = validate(values)
    setErrors(next)
    const first = (Object.keys(LABELS) as (keyof Values)[]).find((key) => next[key])
    if (first) {
      const target = details.event.target as Element
      window.requestAnimationFrame(() => focusField(target, first))
      return
    }
    setPhase("submitting")
    window.setTimeout(() => {
      setSaved(values)
      setPhase("success")
    }, 1200)
  }

  return (
    <Form errors={errors} onFormSubmit={submit} className="gap-4">
      <div>
        <h3 className="text-sm font-semibold text-foreground">Profile</h3>
        <p className="text-sm text-text-secondary">Basic details your team sees on shared projects.</p>
      </div>
        {issues.length > 0 && (
          <Alert variant="negative">
            <AlertTitle>
              Fix {issues.length} {issues.length === 1 ? "field" : "fields"} to continue
            </AlertTitle>
            <AlertDescription>Select an item to jump to the field.</AlertDescription>
            <ul className="flex flex-col gap-1 text-sm">
              {issues.map((key) => (
                <li key={key}>
                  <button type="button" onClick={(event) => focusField(event.currentTarget, key)} className="text-left underline underline-offset-2">
                    {LABELS[key]}: {errors[key]}
                  </button>
                </li>
              ))}
            </ul>
          </Alert>
        )}
      {phase === "success" && (
        <Alert variant="positive">
          <AlertTitle>Profile saved</AlertTitle>
          <AlertDescription>Your changes are live for the whole team.</AlertDescription>
        </Alert>
      )}
      {phase === "failed" && (
        <Alert variant="negative">
          <AlertTitle>We couldn't save your changes</AlertTitle>
          <AlertDescription>Your entries are kept. Check your connection and try again.</AlertDescription>
        </Alert>
      )}
            {FIELDS.map((field) => (
              <Field key={field.key} name={field.key}>
                <FieldLabel>
                  {field.label} <span className="ml-2 text-xs font-normal text-text-tertiary">Required</span>
                </FieldLabel>
                <Input
                  value={values[field.key]}
                  onChange={(event) => change(field.key, event.target.value)}
                  inputMode={field.inputMode}
                  autoComplete={field.autoComplete}
                />
                <FieldDescription>{field.hint}</FieldDescription>
                <FieldError>{errors[field.key]}</FieldError>
              </Field>
            ))}
      <p aria-live="polite" className="flex min-h-5 items-center gap-2 text-xs text-text-secondary">
        {phase === "validating" || phase === "submitting" ? <Spinner className="text-current" /> : null}
        {phase === "validating" && "Checking your entries…"}
        {phase === "submitting" && "Saving…"}
        {phase === "success" && !dirty && "All changes saved"}
        {phase === "idle" && dirty && issues.length === 0 && "You have unsaved changes"}
      </p>
      <FormActions>
        <Button
          type="button"
          variant="plain"
          disabled={phase === "submitting"}
          onClick={() => {
            setValues(saved)
            setErrors({})
            setPhase("idle")
          }}
        >
          Cancel
        </Button>
        <Button type="submit" variant="gradient" pending={phase === "submitting"} disabled={!dirty || phase === "validating"}>
          Save changes
        </Button>
      </FormActions>
    </Form>
  )
}
```

### Validation mode: when a field is checked

```tsx
import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Field, FieldDescription, FieldError, FieldLabel } from "@/components/ui/field"
import { Form } from "@/components/ui/form"
import { FormActions } from "@/components/ui/form-actions"
import { Input } from "@/components/ui/input"

export function Example() {
  const [sent, setSent] = useState("")

  return (
    <Form validationMode="onSubmit" onFormSubmit={(values) => setSent(String(values.email))} className="gap-4">
      <Field name="email">
        <FieldLabel>Work email</FieldLabel>
        <Input type="email" required autoComplete="email" placeholder="name@company.com" onChange={() => setSent("")} />
        <FieldDescription>We send receipts to this address.</FieldDescription>
        <FieldError match="valueMissing">Enter your work email address.</FieldError>
        <FieldError match="typeMismatch">Enter an email address like name@company.com.</FieldError>
      </Field>
      <FormActions align="between">
        <p aria-live="polite" className="text-sm text-text-success">
          {sent ? `Receipts go to ${sent}.` : ""}
        </p>
        <Button type="submit" variant="gradient">
          Save email
        </Button>
      </FormActions>
    </Form>
  )
}
```

### Errors: at the fields, in a summary and for the whole form

```tsx
import { useState } from "react"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import { Button } from "@/components/ui/button"
import { Field, FieldDescription, FieldError, FieldLabel } from "@/components/ui/field"
import { Form } from "@/components/ui/form"
import { FormActions } from "@/components/ui/form-actions"
import { Input } from "@/components/ui/input"
import { Spinner } from "@/components/ui/spinner"

type Values = { name: string; email: string; size: string }
type Errors = Record<string, string>
type Phase = "idle" | "validating" | "submitting" | "success" | "failed"

const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
const LABELS = { name: "Full name", email: "Work email", size: "Team size" } as const
const FIELDS = [
  { key: "name", label: "Full name", hint: "As shown on your invoices.", autoComplete: "name", inputMode: "text" },
  { key: "email", label: "Work email", hint: "We send receipts to this address.", autoComplete: "email", inputMode: "email" },
  { key: "size", label: "Team size", hint: "Between 1 and 50 people.", autoComplete: "off", inputMode: "numeric" },
] as const

function validate(values: Values): Errors {
  const errors: Errors = {}
  if (!values.name.trim()) errors.name = "Enter your full name."
  if (!EMAIL.test(values.email)) errors.email = "Enter a work email address, like name@company.com."
  const size = Number(values.size)
  if (!Number.isInteger(size) || size < 1 || size > 50) errors.size = "Enter a number between 1 and 50."
  return errors
}

export function Example() {
  const [saved, setSaved] = useState<Values>({ name: "Nora Lindgren", email: "info@wunderui.com", size: "12" })
  const [values, setValues] = useState<Values>({ name: "Nora Lindgren", email: "info@wunderui", size: "80" })
  const [errors, setErrors] = useState<Errors>(() => validate({ name: "Nora Lindgren", email: "info@wunderui", size: "80" }))
  const [phase, setPhase] = useState<Phase>("idle")

  const issues = (Object.keys(LABELS) as (keyof Values)[]).filter((key) => errors[key])
  const dirty = (Object.keys(LABELS) as (keyof Values)[]).some((key) => values[key] !== saved[key])

  function focusField(from: Element, key: keyof Values) {
    from.closest("form")?.querySelector<HTMLElement>(`[name="${key}"]`)?.focus()
  }

  function change(key: keyof Values, value: string) {
    setValues((current) => ({ ...current, [key]: value }))
    setErrors((current) => Object.fromEntries(Object.entries(current).filter(([name]) => name !== key)))
    if (phase === "success" || phase === "failed") setPhase("idle")
  }

  function submit(_values: unknown, details: { event: Event }) {
    const next = validate(values)
    setErrors(next)
    const first = (Object.keys(LABELS) as (keyof Values)[]).find((key) => next[key])
    if (first) {
      const target = details.event.target as Element
      window.requestAnimationFrame(() => focusField(target, first))
      return
    }
    setPhase("submitting")
    window.setTimeout(() => {
      setSaved(values)
      setPhase("success")
    }, 1200)
  }

  return (
    <Form errors={errors} onFormSubmit={submit} className="gap-4">
      <div>
        <h3 className="text-sm font-semibold text-foreground">Profile</h3>
        <p className="text-sm text-text-secondary">Basic details your team sees on shared projects.</p>
      </div>
      {phase === "success" && (
        <Alert variant="positive">
          <AlertTitle>Profile saved</AlertTitle>
          <AlertDescription>Your changes are live for the whole team.</AlertDescription>
        </Alert>
      )}
      {phase === "failed" && (
        <Alert variant="negative">
          <AlertTitle>We couldn't save your changes</AlertTitle>
          <AlertDescription>Your entries are kept. Check your connection and try again.</AlertDescription>
        </Alert>
      )}
            {FIELDS.map((field) => (
              <Field key={field.key} name={field.key}>
                <FieldLabel>
                  {field.label} <span className="ml-2 text-xs font-normal text-text-tertiary">Required</span>
                </FieldLabel>
                <Input
                  value={values[field.key]}
                  onChange={(event) => change(field.key, event.target.value)}
                  inputMode={field.inputMode}
                  autoComplete={field.autoComplete}
                />
                <FieldDescription>{field.hint}</FieldDescription>
                <FieldError>{errors[field.key]}</FieldError>
              </Field>
            ))}
      <p aria-live="polite" className="flex min-h-5 items-center gap-2 text-xs text-text-secondary">
        {phase === "validating" || phase === "submitting" ? <Spinner className="text-current" /> : null}
        {phase === "validating" && "Checking your entries…"}
        {phase === "submitting" && "Saving…"}
        {phase === "success" && !dirty && "All changes saved"}
        {phase === "idle" && dirty && issues.length === 0 && "You have unsaved changes"}
      </p>
      <FormActions>
        <Button
          type="button"
          variant="plain"
          disabled={phase === "submitting"}
          onClick={() => {
            setValues(saved)
            setErrors({})
            setPhase("idle")
          }}
        >
          Cancel
        </Button>
        <Button type="submit" variant="gradient" pending={phase === "submitting"} disabled={!dirty || phase === "validating"}>
          Save changes
        </Button>
      </FormActions>
    </Form>
  )
}
```

### Layout: single column, two columns and settings rows

```tsx
import { useState } from "react"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import { Button } from "@/components/ui/button"
import { Field, FieldDescription, FieldError, FieldLabel } from "@/components/ui/field"
import { Form } from "@/components/ui/form"
import { FormActions } from "@/components/ui/form-actions"
import { Input } from "@/components/ui/input"
import { Spinner } from "@/components/ui/spinner"

type Values = { name: string; email: string; size: string }
type Errors = Record<string, string>
type Phase = "idle" | "validating" | "submitting" | "success" | "failed"

const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
const LABELS = { name: "Full name", email: "Work email", size: "Team size" } as const
const FIELDS = [
  { key: "name", label: "Full name", hint: "As shown on your invoices.", autoComplete: "name", inputMode: "text" },
  { key: "email", label: "Work email", hint: "We send receipts to this address.", autoComplete: "email", inputMode: "email" },
  { key: "size", label: "Team size", hint: "Between 1 and 50 people.", autoComplete: "off", inputMode: "numeric" },
] as const

function validate(values: Values): Errors {
  const errors: Errors = {}
  if (!values.name.trim()) errors.name = "Enter your full name."
  if (!EMAIL.test(values.email)) errors.email = "Enter a work email address, like name@company.com."
  const size = Number(values.size)
  if (!Number.isInteger(size) || size < 1 || size > 50) errors.size = "Enter a number between 1 and 50."
  return errors
}

export function Example() {
  const [saved, setSaved] = useState<Values>({ name: "Nora Lindgren", email: "info@wunderui.com", size: "12" })
  const [values, setValues] = useState<Values>({ name: "Nora Lindgren", email: "info@wunderui.com", size: "14" })
  const [errors, setErrors] = useState<Errors>({})
  const [phase, setPhase] = useState<Phase>("idle")

  const issues = (Object.keys(LABELS) as (keyof Values)[]).filter((key) => errors[key])
  const dirty = (Object.keys(LABELS) as (keyof Values)[]).some((key) => values[key] !== saved[key])

  function focusField(from: Element, key: keyof Values) {
    from.closest("form")?.querySelector<HTMLElement>(`[name="${key}"]`)?.focus()
  }

  function change(key: keyof Values, value: string) {
    setValues((current) => ({ ...current, [key]: value }))
    setErrors((current) => Object.fromEntries(Object.entries(current).filter(([name]) => name !== key)))
    if (phase === "success" || phase === "failed") setPhase("idle")
  }

  function submit(_values: unknown, details: { event: Event }) {
    const next = validate(values)
    setErrors(next)
    const first = (Object.keys(LABELS) as (keyof Values)[]).find((key) => next[key])
    if (first) {
      const target = details.event.target as Element
      window.requestAnimationFrame(() => focusField(target, first))
      return
    }
    setPhase("submitting")
    window.setTimeout(() => {
      setSaved(values)
      setPhase("success")
    }, 1200)
  }

  return (
    <Form errors={errors} onFormSubmit={submit} className="gap-4">
      <div>
        <h3 className="text-sm font-semibold text-foreground">Profile</h3>
        <p className="text-sm text-text-secondary">Basic details your team sees on shared projects.</p>
      </div>
        {issues.length > 0 && (
          <Alert variant="negative">
            <AlertTitle>
              Fix {issues.length} {issues.length === 1 ? "field" : "fields"} to continue
            </AlertTitle>
            <AlertDescription>Select an item to jump to the field.</AlertDescription>
            <ul className="flex flex-col gap-1 text-sm">
              {issues.map((key) => (
                <li key={key}>
                  <button type="button" onClick={(event) => focusField(event.currentTarget, key)} className="text-left underline underline-offset-2">
                    {LABELS[key]}: {errors[key]}
                  </button>
                </li>
              ))}
            </ul>
          </Alert>
        )}
      {phase === "success" && (
        <Alert variant="positive">
          <AlertTitle>Profile saved</AlertTitle>
          <AlertDescription>Your changes are live for the whole team.</AlertDescription>
        </Alert>
      )}
      {phase === "failed" && (
        <Alert variant="negative">
          <AlertTitle>We couldn't save your changes</AlertTitle>
          <AlertDescription>Your entries are kept. Check your connection and try again.</AlertDescription>
        </Alert>
      )}
            {FIELDS.map((field) => (
              <Field key={field.key} name={field.key}>
                <FieldLabel>
                  {field.label} <span className="ml-2 text-xs font-normal text-text-tertiary">Required</span>
                </FieldLabel>
                <Input
                  value={values[field.key]}
                  onChange={(event) => change(field.key, event.target.value)}
                  inputMode={field.inputMode}
                  autoComplete={field.autoComplete}
                />
                <FieldDescription>{field.hint}</FieldDescription>
                <FieldError>{errors[field.key]}</FieldError>
              </Field>
            ))}
      <p aria-live="polite" className="flex min-h-5 items-center gap-2 text-xs text-text-secondary">
        {phase === "validating" || phase === "submitting" ? <Spinner className="text-current" /> : null}
        {phase === "validating" && "Checking your entries…"}
        {phase === "submitting" && "Saving…"}
        {phase === "success" && !dirty && "All changes saved"}
        {phase === "idle" && dirty && issues.length === 0 && "You have unsaved changes"}
      </p>
      <FormActions>
        <Button
          type="button"
          variant="plain"
          disabled={phase === "submitting"}
          onClick={() => {
            setValues(saved)
            setErrors({})
            setPhase("idle")
          }}
        >
          Cancel
        </Button>
        <Button type="submit" variant="gradient" pending={phase === "submitting"} disabled={!dirty || phase === "validating"}>
          Save changes
        </Button>
      </FormActions>
    </Form>
  )
}
```

## In context

### Profile: check, save and confirm

Clear the email or set the team size to 80 and press Save. The summary lists the fields, focus moves to the first one and messages clear as you fix them, and a valid form saves in about a second.

```tsx
import { useState } from "react"
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert"
import { Button } from "@/components/ui/button"
import { Field, FieldDescription, FieldError, FieldLabel } from "@/components/ui/field"
import { Form } from "@/components/ui/form"
import { FormActions } from "@/components/ui/form-actions"
import { Input } from "@/components/ui/input"
import { Spinner } from "@/components/ui/spinner"

type Values = { name: string; email: string; size: string }
type Errors = Record<string, string>
type Phase = "idle" | "validating" | "submitting" | "success" | "failed"

const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
const LABELS = { name: "Full name", email: "Work email", size: "Team size" } as const
const FIELDS = [
  { key: "name", label: "Full name", hint: "As shown on your invoices.", autoComplete: "name", inputMode: "text" },
  { key: "email", label: "Work email", hint: "We send receipts to this address.", autoComplete: "email", inputMode: "email" },
  { key: "size", label: "Team size", hint: "Between 1 and 50 people.", autoComplete: "off", inputMode: "numeric" },
] as const

function validate(values: Values): Errors {
  const errors: Errors = {}
  if (!values.name.trim()) errors.name = "Enter your full name."
  if (!EMAIL.test(values.email)) errors.email = "Enter a work email address, like name@company.com."
  const size = Number(values.size)
  if (!Number.isInteger(size) || size < 1 || size > 50) errors.size = "Enter a number between 1 and 50."
  return errors
}

export function Example() {
  const [saved, setSaved] = useState<Values>({ name: "Nora Lindgren", email: "info@wunderui.com", size: "12" })
  const [values, setValues] = useState<Values>({ name: "Nora Lindgren", email: "info@wunderui.com", size: "14" })
  const [errors, setErrors] = useState<Errors>({})
  const [phase, setPhase] = useState<Phase>("idle")

  const issues = (Object.keys(LABELS) as (keyof Values)[]).filter((key) => errors[key])
  const dirty = (Object.keys(LABELS) as (keyof Values)[]).some((key) => values[key] !== saved[key])

  function focusField(from: Element, key: keyof Values) {
    from.closest("form")?.querySelector<HTMLElement>(`[name="${key}"]`)?.focus()
  }

  function change(key: keyof Values, value: string) {
    setValues((current) => ({ ...current, [key]: value }))
    setErrors((current) => Object.fromEntries(Object.entries(current).filter(([name]) => name !== key)))
    if (phase === "success" || phase === "failed") setPhase("idle")
  }

  function submit(_values: unknown, details: { event: Event }) {
    const next = validate(values)
    setErrors(next)
    const first = (Object.keys(LABELS) as (keyof Values)[]).find((key) => next[key])
    if (first) {
      const target = details.event.target as Element
      window.requestAnimationFrame(() => focusField(target, first))
      return
    }
    setPhase("submitting")
    window.setTimeout(() => {
      setSaved(values)
      setPhase("success")
    }, 1200)
  }

  return (
    <Form errors={errors} onFormSubmit={submit} className="gap-4">
      <div>
        <h3 className="text-sm font-semibold text-foreground">Profile</h3>
        <p className="text-sm text-text-secondary">Basic details your team sees on shared projects.</p>
      </div>
        {issues.length > 0 && (
          <Alert variant="negative">
            <AlertTitle>
              Fix {issues.length} {issues.length === 1 ? "field" : "fields"} to continue
            </AlertTitle>
            <AlertDescription>Select an item to jump to the field.</AlertDescription>
            <ul className="flex flex-col gap-1 text-sm">
              {issues.map((key) => (
                <li key={key}>
                  <button type="button" onClick={(event) => focusField(event.currentTarget, key)} className="text-left underline underline-offset-2">
                    {LABELS[key]}: {errors[key]}
                  </button>
                </li>
              ))}
            </ul>
          </Alert>
        )}
      {phase === "success" && (
        <Alert variant="positive">
          <AlertTitle>Profile saved</AlertTitle>
          <AlertDescription>Your changes are live for the whole team.</AlertDescription>
        </Alert>
      )}
      {phase === "failed" && (
        <Alert variant="negative">
          <AlertTitle>We couldn't save your changes</AlertTitle>
          <AlertDescription>Your entries are kept. Check your connection and try again.</AlertDescription>
        </Alert>
      )}
            {FIELDS.map((field) => (
              <Field key={field.key} name={field.key}>
                <FieldLabel>
                  {field.label} <span className="ml-2 text-xs font-normal text-text-tertiary">Required</span>
                </FieldLabel>
                <Input
                  value={values[field.key]}
                  onChange={(event) => change(field.key, event.target.value)}
                  inputMode={field.inputMode}
                  autoComplete={field.autoComplete}
                />
                <FieldDescription>{field.hint}</FieldDescription>
                <FieldError>{errors[field.key]}</FieldError>
              </Field>
            ))}
      <p aria-live="polite" className="flex min-h-5 items-center gap-2 text-xs text-text-secondary">
        {phase === "validating" || phase === "submitting" ? <Spinner className="text-current" /> : null}
        {phase === "validating" && "Checking your entries…"}
        {phase === "submitting" && "Saving…"}
        {phase === "success" && !dirty && "All changes saved"}
        {phase === "idle" && dirty && issues.length === 0 && "You have unsaved changes"}
      </p>
      <FormActions>
        <Button
          type="button"
          variant="plain"
          disabled={phase === "submitting"}
          onClick={() => {
            setValues(saved)
            setErrors({})
            setPhase("idle")
          }}
        >
          Cancel
        </Button>
        <Button type="submit" variant="gradient" pending={phase === "submitting"} disabled={!dirty || phase === "validating"}>
          Save changes
        </Button>
      </FormActions>
    </Form>
  )
}
```

### Invite: a rule only the server knows

The server answers with one message per field name, and Form hands it to the Field with that name. Send the invite to priya.raman@wunderui.com to see it, then to any other address.

```tsx
import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Field, FieldDescription, FieldError, FieldLabel } from "@/components/ui/field"
import { Form } from "@/components/ui/form"
import { FormActions } from "@/components/ui/form-actions"
import { Input } from "@/components/ui/input"

// The server answers with one message per field name. Form hands each message to the Field with that name.
function inviteOnServer(email: string): Promise<Record<string, string>> {
  return new Promise((resolve) =>
    window.setTimeout(
      () => resolve(email === "priya.raman@wunderui.com" ? { email: "Priya Raman is already a member of WunderUI." } : {}),
      900
    )
  )
}

export function Example() {
  const [errors, setErrors] = useState<Record<string, string>>({})
  const [pending, setPending] = useState(false)
  const [invited, setInvited] = useState("")

  return (
    <Form
      errors={errors}
      className="gap-4"
      onFormSubmit={async (values) => {
        setPending(true)
        setInvited("")
        const result = await inviteOnServer(String(values.email))
        setPending(false)
        setErrors(result)
        if (Object.keys(result).length === 0) setInvited(String(values.email))
      }}
    >
      <Field name="email">
        <FieldLabel>Teammate email</FieldLabel>
        <Input type="email" required autoComplete="off" placeholder="name@company.com" onChange={() => setErrors({})} />
        <FieldDescription>They get an invite that works for seven days. Try priya.raman@wunderui.com.</FieldDescription>
        <FieldError match="valueMissing">Enter the email address of the person to invite.</FieldError>
        <FieldError match="typeMismatch">Enter an email address like name@company.com.</FieldError>
        <FieldError match={Boolean(errors.email)}>{errors.email}</FieldError>
      </Field>
      <FormActions align="between">
        <p aria-live="polite" className="text-sm text-text-success">
          {invited ? `Invite sent to ${invited}.` : ""}
        </p>
        <Button type="submit" variant="gradient" pending={pending}>
          Send invite
        </Button>
      </FormActions>
    </Form>
  )
}
```

### Settings: a bar for unsaved changes

The bar sticks to the bottom of the form as soon as a field differs from what is saved, and goes away after Save or Discard. Change the workspace name to see it.

```tsx
import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Field, FieldDescription, FieldLabel } from "@/components/ui/field"
import { Form } from "@/components/ui/form"
import { FormActions } from "@/components/ui/form-actions"
import { Input } from "@/components/ui/input"

const SAVED = { workspace: "WunderUI", billing: "info@wunderui.com" }

export function Example() {
  const [values, setValues] = useState(SAVED)
  const [saved, setSaved] = useState(SAVED)
  const dirty = values.workspace !== saved.workspace || values.billing !== saved.billing

  return (
    <Form className="gap-4" onFormSubmit={() => setSaved(values)}>
      <Field name="workspace">
        <FieldLabel>Workspace name</FieldLabel>
        <Input value={values.workspace} onChange={(event) => setValues({ ...values, workspace: event.target.value })} />
        <FieldDescription>Shown in the sidebar and on invoices.</FieldDescription>
      </Field>
      <Field name="billing">
        <FieldLabel>Billing email</FieldLabel>
        <Input value={values.billing} onChange={(event) => setValues({ ...values, billing: event.target.value })} inputMode="email" />
        <FieldDescription>Receipts and renewal notices go here.</FieldDescription>
      </Field>
      {dirty && (
        <FormActions align="between" className="sticky bottom-0 -mx-4 border-t border-border bg-card px-4 py-3">
          <p role="status" className="text-sm text-text-secondary">
            You have unsaved changes
          </p>
          <div className="flex items-center gap-2">
            <Button type="button" variant="plain" onClick={() => setValues(saved)}>
              Discard
            </Button>
            <Button type="submit" variant="gradient">
              Save changes
            </Button>
          </div>
        </FormActions>
      )}
    </Form>
  )
}
```

## For AI agents

`get_component("form")`

Hand your agent this page as Markdown or the WunderUI MCP server, not a screenshot.
