# Forms

Order fields, labels, and actions so a person completes a form in one pass.

## Overview

Ask only for the values the task needs. Remove every field you can derive, default, or ask for later.

This page covers layout, labels, save models, and actions. [Errors and Validation](/docs/patterns/errors-and-validation) covers checking values and reporting problems.

## Choosing a Control

Choose the control from the shape of the value, not from its look.

* **Free Text (TextInput):** For a name or address. Use a [Textarea](/docs/components/textarea) for a longer memo.
* **An Amount of Money (AmountInput):** [AmountInput](/docs/components/amount-input) sets a decimal keyboard and rejects anything that is not a number.
* **Five or Fewer Options (RadioGroup):** A [RadioGroup](/docs/components/radio-group) keeps every choice visible.
* **Many Options (Select):** A [Select](/docs/components/select). If people need to search, use a [Combobox](/docs/components/combobox).

**Do:** Show a short set of exclusive options in a [RadioGroup](/docs/components/radio-group).

```tsx
<Fieldset.Root>
  <Fieldset.Legend>Network fee</Fieldset.Legend>
  <RadioGroup.Root aria-label="Network fee" defaultValue="standard">
    <Field.Root>
      <Field.Item>
        <RadioGroup.Item value="standard" />
        <Field.Label>Standard</Field.Label>
      </Field.Item>
    </Field.Root>
    <Field.Root>
      <Field.Item>
        <RadioGroup.Item value="fast" />
        <Field.Label>Fast</Field.Label>
      </Field.Item>
    </Field.Root>
  </RadioGroup.Root>
</Fieldset.Root>
```

**Don't:** Use a [Checkbox](/docs/components/checkbox) for options that exclude each other.

```tsx
<Fieldset.Root>
  <Fieldset.Legend>Network fee</Fieldset.Legend>
  <Field.Root>
    <Field.Item>
      <Checkbox defaultChecked />
      <Field.Label>Standard</Field.Label>
    </Field.Item>
  </Field.Root>
  <Field.Root>
    <Field.Item>
      <Checkbox />
      <Field.Label>Fast</Field.Label>
    </Field.Item>
  </Field.Root>
</Fieldset.Root>
```

### Help Browsers Fill Values

Set `type`, `inputMode`, and `autoComplete` on each `TextInput.Control`, so browsers suggest saved values and phones show the matching keyboard.

* **Personal Data (autoComplete):** Name each value, such as `autoComplete="email"`, as WCAG 2.2 requires for personal data.
* **Machine Values (spellCheck):** Turn off spell check and set `autoComplete="off"` for addresses, API keys, and other machine values.

## Structure

1. **Title:** Names the task, such as New webhook, and states the result of submit.
2. **Fields:** One column, in answer order, with related fields grouped.
3. **Each field:** Label, control, then a description or an error.
4. **Actions:** After the last field, in the [action order](#order-actions).

```tsx
import { Button, Checkbox, Field, Fieldset, Frame, Stack, style, Surface, Textarea, TextInput, Toast } from '@tempoxyz/ds'
import { useState } from 'react'

export const fill = true
const events = [
  ['payment.received', 'Payment received'],
  ['payment.sent', 'Payment sent'],
  ['transfer.failed', 'Transfer failed'],
] as const

function valid(url: string) {
  return /^https:\/\/[^\s/]+\.[^\s]+$/.test(url)
}

function WebhookForm() {
  const toast = Toast.useToast()
  const [invalid, setInvalid] = useState(false)
  const [pending, setPending] = useState(false)
  const [submitted, setSubmitted] = useState(false)
  const [url, setUrl] = useState('')

  return (
    <Surface
      {...styles.form()}
      render={
        <form
          noValidate
          onSubmit={(event) => {
            event.preventDefault()
            setSubmitted(true)

            if (!valid(url)) {
              setInvalid(true)
              event.currentTarget.querySelector<HTMLInputElement>('input[name="url"]')?.focus()
              return
            }

            setPending(true)
            setTimeout(() => {
              setPending(false)
              toast.add({ description: url, intent: 'positive', title: 'Webhook created' })
            }, 1200)
          }}
        />
      }
    >
      <Frame.Root>
        <Frame.Header>
          <Frame.Title>New webhook</Frame.Title>
          <Frame.Description>
            Tempo sends a POST request to your endpoint for each event you choose.
          </Frame.Description>
        </Frame.Header>
        <Fieldset.Root disabled={pending}>
          <Fieldset.Legend>Endpoint</Fieldset.Legend>
          <Field.Root invalid={invalid}>
            <Field.Label>Endpoint URL</Field.Label>
            <TextInput.Group>
              <TextInput.Control
                autoComplete="off"
                name="url"
                onValueChange={(value) => {
                  setUrl(value)
                  // After the first submit, the error clears as soon as the value is fixed.
                  if (submitted) setInvalid(!valid(value))
                }}
                placeholder="https://api.example.com/tempo"
                required
                spellCheck={false}
                type="url"
                value={url}
              />
            </TextInput.Group>
            <Field.Description>Use an HTTPS URL on a server you control.</Field.Description>
            <Field.Error match={invalid}>Enter a URL that starts with https://.</Field.Error>
          </Field.Root>
          <Field.Root>
            <Field.Label>Description (optional)</Field.Label>
            <Textarea name="description" placeholder="Order fulfillment" rows={2} />
          </Field.Root>
        </Fieldset.Root>
        <Fieldset.Root disabled={pending}>
          <Fieldset.Legend>Events</Fieldset.Legend>
          <Stack gap="12">
            {events.map(([value, label]) => (
              <Field.Root key={value}>
                <Field.Item>
                  <Checkbox defaultChecked={value === 'payment.received'} name={value} />
                  <Field.Label>{label}</Field.Label>
                </Field.Item>
              </Field.Root>
            ))}
          </Stack>
        </Fieldset.Root>
        <Frame.Footer>
          <Frame.Actions {...styles.actions()}>
            <Button type="button" variant="secondary">
              Cancel
            </Button>
            <Button loading={pending} type="submit">
              Create webhook
            </Button>
          </Frame.Actions>
        </Frame.Footer>
      </Frame.Root>
    </Surface>
  )
}

export function Demo() {
  return (
    <div {...styles.page()}>
      <Toast.Provider>
        <WebhookForm />
        <Toast.Viewport />
      </Toast.Provider>
    </div>
  )
}

namespace styles {
  // Below 640px the actions stack at full width with the primary action on top. From 640px they sit
  // at the end at their content width.
  export const actions = style({
    flexDirection: 'column-reverse',
    rowGap: '8',
    selectors: { '& > *': { flexBasis: 'auto !custom', width: '100% !custom' } },
    '@media (min-width: 40rem)': {
      flexDirection: 'row',
      justifyContent: 'flex-end',
      selectors: { '& > *': { flexGrow: '0 !custom', width: 'auto !custom' } },
    },
  })

  export const form = style({
    boxSizing: 'border-box',
    maxWidth: '30rem !custom',
    width: '100% !custom',
  })

  export const page = style({
    backgroundColor: 'background.primary',
    display: 'grid',
    justifyItems: 'center',
    padding: '16',
  })
}
```

[View example source](https://github.com/tempoxyz/ds/blob/main/docs/src/examples/demos/Patterns/WebhookForm.tsx)

This reference layout uses [Surface](/docs/components/surface), [Frame](/docs/components/frame), [Fieldset](/docs/components/fieldset), and [Field](/docs/components/field). Submit an empty URL to show the error, then fix the URL to clear it.

### Use One Column

Stack fields in a single column, in the order a person expects, such as recipient, then amount, then memo. Put two fields on one row only if they form one short value, such as a month and a year. If people enter several records with the same fields, such as batch payout recipients, use an [editable table](/docs/patterns/tables-and-lists#edit-rows-in-place).

**Do:** Stack fields in one column, in the order you answer them.

```tsx
/**
 * Do example for "Use One Column" on the Forms page.
 * Stack fields in one column, in the order you answer them.
 * @module
 */
import { Field, Stack, style, TextInput } from '@tempoxyz/ds'

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <Stack gap="24" {...styles.fill()}>
      <Field.Root>
        <Field.Label>Recipient</Field.Label>
        <TextInput.Group>
          <TextInput.Control placeholder="0x…" />
        </TextInput.Group>
      </Field.Root>
      <Field.Root>
        <Field.Label>Amount</Field.Label>
        <TextInput.Group>
          <TextInput.Control inputMode="decimal" placeholder="0.00" />
          <TextInput.Suffix>USDC</TextInput.Suffix>
        </TextInput.Group>
      </Field.Root>
    </Stack>
  )
}

namespace styles {
  export const fill = style({ width: '100% !custom' })
}
```

**Don't:** Arrange unrelated fields in a grid, where the reading order is unclear.

```tsx
/**
 * Don't example for "Use One Column" on the Forms page.
 * Don't arrange unrelated fields in a grid, where the reading order is unclear.
 * @module
 */
import { Field, style, TextInput } from '@tempoxyz/ds'

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <div {...styles.grid()}>
      <Field.Root>
        <Field.Label>Recipient</Field.Label>
        <TextInput.Group>
          <TextInput.Control placeholder="0x…" />
        </TextInput.Group>
      </Field.Root>
      <Field.Root>
        <Field.Label>Amount</Field.Label>
        <TextInput.Group>
          <TextInput.Control inputMode="decimal" placeholder="0.00" />
        </TextInput.Group>
      </Field.Root>
      <Field.Root>
        <Field.Label>Memo</Field.Label>
        <TextInput.Group>
          <TextInput.Control placeholder="Invoice 1042" />
        </TextInput.Group>
      </Field.Root>
      <Field.Root>
        <Field.Label>Fee token</Field.Label>
        <TextInput.Group>
          <TextInput.Control placeholder="PathUSD" />
        </TextInput.Group>
      </Field.Root>
    </div>
  )
}

namespace styles {
  export const grid = style({
    display: 'grid',
    gap: '16',
    gridTemplateColumns: 'repeat(2, minmax(0, 1fr)) !custom',
    width: '100% !custom',
  })
}
```

### Group Related Fields

Wrap the parts of one idea, such as an address, in a [Fieldset](/docs/components/fieldset) with a `Fieldset.Legend`. Set `variant` once on the fieldset, which passes it to every nested `Field.Root`. If a form outgrows two or three groups, split it into steps with a [Stepper](/docs/components/stepper).

**Do:** Group related fields under one legend and one variant.

```tsx
<Fieldset.Root>
  <Fieldset.Legend>Recipient</Fieldset.Legend>
  <Field.Root>
    <Field.Label>Name</Field.Label>
    <TextInput.Group>
      <TextInput.Control />
    </TextInput.Group>
  </Field.Root>
  <Field.Root>
    <Field.Label>Email</Field.Label>
    <TextInput.Group>
      <TextInput.Control type="email" />
    </TextInput.Group>
  </Field.Root>
</Fieldset.Root>
```

**Don't:** Mix field variants within one group.

```tsx
<Fieldset.Root>
  <Fieldset.Legend>Recipient</Fieldset.Legend>
  <Field.Root>
    <Field.Label>Name</Field.Label>
    <TextInput.Group>
      <TextInput.Control />
    </TextInput.Group>
  </Field.Root>
  <Field.Root>
    <Field.Label>Email</Field.Label>
    <TextInput.Group>
      <TextInput.Control type="email" />
    </TextInput.Group>
  </Field.Root>
</Fieldset.Root>
```

## Labels and Help Text

Every control needs a visible `Field.Label`, written as a short noun. Put format hints in `Field.Description`. A placeholder holds only an example value, such as `0x…` or `https://`.

### Put Labels Above Fields

[Field](/docs/components/field) puts the label 12px above every control. The label stays visible during input, and long labels wrap without narrowing the control.

* **Text Field (TextInput):** The label sits above the field, and the message below it.
* **Switch (Switch):** The label sits above the switch, as it does above a text field.

**Do:** Give every control a visible `Field.Label`, with format hints in `Field.Description`.

```tsx
/**
 * Do example for "Put Labels Above Fields" on the Forms page.
 * Give every control a visible `Field.Label`, with format hints in `Field.Description`.
 * @module
 */
import { Field, style, TextInput } from '@tempoxyz/ds'

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <Field.Root {...styles.fill()}>
      <Field.Label>Recipient address</Field.Label>
      <TextInput.Group>
        <TextInput.Control placeholder="0x…" />
      </TextInput.Group>
      <Field.Description>A Tempo address that starts with 0x.</Field.Description>
    </Field.Root>
  )
}

namespace styles {
  export const fill = style({ width: '100% !custom' })
}
```

**Don't:** Use a placeholder as the label. It disappears on input.

```tsx
/**
 * Don't example for "Put Labels Above Fields" on the Forms page.
 * Don't use a placeholder as the label. It disappears on input.
 * @module
 */
import { style, TextInput } from '@tempoxyz/ds'

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <TextInput.Group {...styles.fill()}>
      <TextInput.Control aria-label="Recipient address" placeholder="Recipient address" />
    </TextInput.Group>
  )
}

namespace styles {
  export const fill = style({ width: '100% !custom' })
}
```

### Mark Optional Fields

Most fields are required, so mark the exceptions. Set `required` on required controls, so assistive technology announces them. Set `noValidate` on the `<form>`, so browser validation popups do not replace `Field.Error`. If every field is optional, such as on a filter form, state this once in the description.

**Do:** Write (optional) in the label of each optional field.

```tsx
/**
 * Do example for "Mark Optional Fields" on the Forms page.
 * Write (optional) in the label of each optional field.
 * @module
 */
import { Field, Stack, style, TextInput } from '@tempoxyz/ds'

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <Stack gap="24" {...styles.fill()}>
      <Field.Root>
        <Field.Label>Key name</Field.Label>
        <TextInput.Group>
          <TextInput.Control defaultValue="Production" required />
        </TextInput.Group>
      </Field.Root>
      <Field.Root>
        <Field.Label>Expires (optional)</Field.Label>
        <TextInput.Group>
          <TextInput.Control placeholder="YYYY-MM-DD" />
        </TextInput.Group>
      </Field.Root>
    </Stack>
  )
}

namespace styles {
  export const fill = style({ width: '100% !custom' })
}
```

**Don't:** Mark required fields with an asterisk and leave optional fields unmarked.

```tsx
/**
 * Don't example for "Mark Optional Fields" on the Forms page.
 * Don't mark required fields with an asterisk and leave optional fields unmarked.
 * @module
 */
import { Field, Stack, style, TextInput } from '@tempoxyz/ds'

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <Stack gap="24" {...styles.fill()}>
      <Field.Root>
        <Field.Label>Key name *</Field.Label>
        <TextInput.Group>
          <TextInput.Control defaultValue="Production" />
        </TextInput.Group>
      </Field.Root>
      <Field.Root>
        <Field.Label>Expires</Field.Label>
        <TextInput.Group>
          <TextInput.Control placeholder="YYYY-MM-DD" />
        </TextInput.Group>
      </Field.Root>
    </Stack>
  )
}

namespace styles {
  export const fill = style({ width: '100% !custom' })
}
```

## Settings

### Choose a Save Model

* **Save on Submit (Checkbox):** For values that work together. Nothing changes until you press the primary action.
* **Save on Change (Switch):** For independent settings. Confirm each change with a [Toast](/docs/components/toast), and revert it if it fails.

Do not mix the two in one section. If a person leaves a long form with unsaved changes, confirm the discard (see [Destructive Actions](/docs/patterns/destructive-actions)).

**Do:** Use a [Switch](/docs/components/switch) for a setting that applies immediately.

```tsx
<Field.Root>
  <Field.Label>Payment alerts</Field.Label>
  <Switch defaultChecked />
  <Field.Description>Email me when a payment is confirmed.</Field.Description>
</Field.Root>
```

**Don't:** Pair a switch with a save button. If a change waits for submit, use a checkbox.

```tsx
<Field.Root>
  <Field.Label>Payment alerts</Field.Label>
  <Switch defaultChecked />
  <Field.Description>Email me when a payment is confirmed.</Field.Description>
</Field.Root>
<Button size="small">Save changes</Button>
```

## Submitting

Keep the submit button enabled and validate on press (see [Errors and Validation](/docs/patterns/errors-and-validation#keep-submit-buttons-enabled)). Set `loading` on it while the request runs, to block a second submit.

### Order Actions

This order applies to every action group, including forms, dialog footers, and toolbars. Keep it the same across every page of a product.

* **Alignment:** Align the group to the end, after the last field.
* **Order:** Put Cancel or Back before the primary action, so the primary action comes last.
* **Below 640px:** Stack the actions at full width, with the primary action first.

**Do:** Align actions to the end, with Cancel before the primary action.

```tsx
/**
 * Do example for "Order Actions" on the Forms page.
 * Align actions to the end, with Cancel before the primary action.
 * @module
 */
import { Button, Field, Stack, style, TextInput } from '@tempoxyz/ds'

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <Stack gap="24" {...styles.fill()}>
      <Field.Root>
        <Field.Label>Endpoint URL</Field.Label>
        <TextInput.Group>
          <TextInput.Control defaultValue="https://api.example.com/tempo" />
        </TextInput.Group>
      </Field.Root>
      <div {...styles.actions()}>
        <Button variant="secondary">Cancel</Button>
        <Button>Create webhook</Button>
      </div>
    </Stack>
  )
}

namespace styles {
  export const actions = style({ columnGap: '8', display: 'flex', justifyContent: 'flex-end' })

  export const fill = style({ width: '100% !custom' })
}
```

**Don't:** Put the primary action first and push Cancel to the far edge.

```tsx
/**
 * Don't example for "Order Actions" on the Forms page.
 * Don't put the primary action first and push Cancel to the far edge.
 * @module
 */
import { Button, Field, Stack, style, TextInput } from '@tempoxyz/ds'

/** Renders the static preview, which the guideline card shows inert. */
export function Demo() {
  return (
    <Stack gap="24" {...styles.fill()}>
      <Field.Root>
        <Field.Label>Endpoint URL</Field.Label>
        <TextInput.Group>
          <TextInput.Control defaultValue="https://api.example.com/tempo" />
        </TextInput.Group>
      </Field.Root>
      <div {...styles.actions()}>
        <Button>Create webhook</Button>
        <Button variant="secondary">Cancel</Button>
      </div>
    </Stack>
  )
}

namespace styles {
  export const actions = style({ display: 'flex', justifyContent: 'space-between' })

  export const fill = style({ width: '100% !custom' })
}
```

### Name the Result in the Button

Use one primary button, so Enter submits the form. Label it with the result, such as Create webhook.

**Do:** Name the result of the form in the button.

```tsx
<Button>Send payment</Button>
```

**Don't:** Use a generic label that hides what happens.

```tsx
<Button>Submit</Button>
```

## States

* **Default:** Prefill a value when it is known, such as the connected address.
* **Loading (Skeleton):** Wrap each control in a [Skeleton](/docs/components/skeleton) while saved values load.
* **Error (Field.Error):** An error under each invalid field (see [Errors and Validation](/docs/patterns/errors-and-validation)).
* **Disabled (disabled):** Set it on a fieldset to disable a whole group, and state the reason nearby.
* **Success (success):** Close the form and confirm with a [Toast](/docs/components/toast). `success` sets no ARIA state, so confirm in text too.

## Content

* **Nouns and Verbs:** Label fields with nouns and buttons with verbs.
* **One Sentence:** Keep each description to a single sentence.

## Accessibility

* **Visible Labels (label):** Pressing a label focuses its control. A field without a visible label, such as search, needs an `aria-label`.
* **Announced Help (aria-describedby):** Screen readers read the description and any shown error with the control.
* **Named Groups (Fieldset.Legend):** Names the native fieldset. Write it as the topic of the group.
* **Matching Order (Tab):** Keep the visual order the same as the DOM order, so focus moves down one field at a time.

## Related

[Field](/docs/components/field)

Use for labels, descriptions, and errors.

[Fieldset](/docs/components/fieldset)

Use for grouping fields.

[TextInput](/docs/components/text-input)

Use for text.

[AmountInput](/docs/components/amount-input)

Use for amounts of money.

[Button](/docs/components/button)

Use for submit and cancel actions.

[Errors and Validation](/docs/patterns/errors-and-validation)

Covers checking values.

[Loading](/docs/patterns/loading)

Covers submit and load states.
