# Forms

How Nacre forms ask, check and recover: labels that stay, errors that arrive at the right moment, and one place that lists everything to fix.

## Every field has the same four parts

A label above, the control, then one line under it that is either the hint or the error. The error takes the hint's place, so the form does not jump by a line when something goes wrong.

All six form controls share one error API. error is the message: it colours the control, sets aria-invalid and is linked with aria-describedby. invalid only marks the control, for the cases where a group or a summary owns the words.

- Labels are always visible. A placeholder is an example of the format, never the label.
- When most fields are required, mark the optional ones instead.
- Every control takes ref as a plain prop, so a form can move focus to the field it is talking about.

## Check on blur, then live

Nothing is wrong while someone is still typing. The first check runs when they leave the field. After that the field re-checks on every key, so the error goes away the moment the value is right.

Submit checks everything, including required fields that were never touched.

- Do: Say what to do: Enter a full email address, such as dara@studio.co.
- Avoid: Say only what is wrong: Invalid input.
- Do: Keep the hint short enough that the error can replace it in the same place.
- Avoid: Show the hint and the error together under one field.

### Demo: Invite by email

Type part of an address and press Tab. Then finish the address and watch the message clear.

```tsx
'use client'
import { useRef, useState, type FormEvent } from 'react'
import { Button } from '@/nacre/components/Button'
import { Input } from '@/nacre/components/Input'

// Check on blur, then live. The first check waits until the person leaves the field (no error while they are still
// typing); after that every key re-checks, so the message goes away the moment the value is right. Submit checks all,
// including an empty required field, and a failed submit moves focus to the field so its message is read with it.
// Leaving an empty field without typing is not an error yet.

const EMAIL = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/

function checkEmail(v: string): string | undefined {
  if (!v.trim()) return 'Enter the email address to invite.'
  if (!EMAIL.test(v.trim())) return 'Enter a full email address, such as dara@studio.co.'
  return undefined
}

export function ValidationTiming() {
  const [value, setValue] = useState('')
  const [touched, setTouched] = useState(false)
  const [sent, setSent] = useState('')
  const field = useRef<HTMLInputElement>(null)
  const error = touched ? checkEmail(value) : undefined
  const submit = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    setTouched(true)
    // After the render that marks it invalid, so the field is read with its message.
    if (checkEmail(value)) return void requestAnimationFrame(() => field.current?.focus())
    setSent(`Invite sent to ${value.trim()}.`)
    setValue('')
    setTouched(false)
  }
  return (
    <form noValidate onSubmit={submit} className="flex w-full max-w-[24rem] flex-col gap-4">
      <Input
        ref={field}
        label="Invite by email"
        type="email"
        autoComplete="off"
        placeholder="name@company.com"
        hint="They get a link that works for seven days."
        value={value}
        error={error}
        onChange={(e) => { setValue(e.target.value); setSent('') }}
        onBlur={() => { if (value) setTouched(true) }}
      />
      <div className="flex flex-wrap items-center gap-3">
        <Button type="submit">Send invite</Button>
        <p role="status" className="text-caption text-fg-muted">{sent}</p>
      </div>
    </form>
  )
}
```

## Summarise when the form is long

When a form is taller than the screen, a failed submit puts an error Alert at the top and moves focus to it. It names each problem as a button that moves focus to that field.

The summary is live: fixing a field removes its line straight away. When the last line goes, the Alert goes too.

### Demo: New project

Press Create project with the form empty, then use the buttons in the summary to jump to each field.

```tsx
'use client'
import { useEffect, useRef, useState, type FormEvent } from 'react'
import { Alert } from '@/nacre/components/Alert'
import { Button } from '@/nacre/components/Button'
import { Input } from '@/nacre/components/Input'
import { RadioGroup } from '@/nacre/components/Radio'
import { Select } from '@/nacre/components/Select'

// A form taller than one screen gets a summary on submit: an error Alert at the top that takes focus, names every
// problem, and moves focus to the field when a problem is pressed. Each field also shows its own message, and fixing
// a field removes its line from the summary at once. Refs are plain props (React 19).

type Field = 'name' | 'owner' | 'visibility'
type Errors = Partial<Record<Field, string>>
type Values = Record<Field, string>

const EMPTY: Values = { name: '', owner: '', visibility: '' }
const OWNERS = [
  { value: 'ana', label: 'Ana Ribeiro' },
  { value: 'ben', label: 'Ben Okafor' },
  { value: 'chen', label: 'Chen Wei' },
  { value: 'dara', label: 'Dara Novak' },
]
const VISIBILITY = [
  { value: 'team', label: 'Everyone in Nacre', description: 'Six people can open it.' },
  { value: 'private', label: 'Only people I invite' },
]
const LABELS: Record<Field, string> = { name: 'Project name', owner: 'Owner', visibility: 'Who can see it' }

function validate(v: Values): Errors {
  const e: Errors = {}
  if (v.name.trim().length < 3) e.name = 'Use at least three characters for the project name.'
  if (!v.owner) e.owner = 'Choose who owns this project.'
  if (!v.visibility) e.visibility = 'Choose who can see the project.'
  return e
}

export function ErrorSummary() {
  const [values, setValues] = useState<Values>(EMPTY)
  const [errors, setErrors] = useState<Errors>({})
  const [submitted, setSubmitted] = useState(false)
  const [created, setCreated] = useState('')
  const [form, setForm] = useState(0)
  const summary = useRef<HTMLDivElement>(null)
  const success = useRef<HTMLDivElement>(null)
  const name = useRef<HTMLInputElement>(null)
  // The button that was pressed goes away on success and on reset, so focus moves to what replaced it: the success
  // Alert (focus reads it, so it has no live role and is not announced twice), then the first field again.
  const next = useRef<'success' | 'name' | null>(null)
  useEffect(() => {
    if (next.current === 'success') success.current?.focus()
    if (next.current === 'name') name.current?.focus()
    next.current = null
  }, [created])
  const owner = useRef<HTMLSelectElement>(null)
  const visibility = useRef<HTMLFieldSetElement>(null)
  const focusField = (f: Field) => {
    if (f === 'name') name.current?.focus()
    else if (f === 'owner') owner.current?.focus()
    else visibility.current?.querySelector<HTMLInputElement>('input:not(:disabled)')?.focus()
  }
  const set = (f: Field, v: string) => {
    const next = { ...values, [f]: v }
    setValues(next)
    if (submitted) setErrors(validate(next))
  }
  const submit = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    const found = validate(values)
    setSubmitted(true)
    setErrors(found)
    if (Object.keys(found).length) {
      requestAnimationFrame(() => summary.current?.focus())
      return
    }
    next.current = 'success'
    setCreated(values.name.trim())
  }
  const reset = () => {
    if (created) next.current = 'name'
    setValues(EMPTY)
    setErrors({})
    setSubmitted(false)
    setCreated('')
    setForm((n) => n + 1)
  }
  const problems = (Object.keys(LABELS) as Field[]).filter((f) => errors[f])
  if (created) {
    return (
      <div className="flex w-full max-w-[28rem] flex-col gap-4">
        <Alert
          ref={success}
          tabIndex={-1}
          tone="success"
          className="outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus"
          title={`${created} is ready`}
          description="The owner can add tasks now, and everyone you chose can open it."
        />
        <div><Button variant="secondary" onClick={reset}>Start another project</Button></div>
      </div>
    )
  }
  return (
    <form key={form} noValidate onSubmit={submit} className="flex w-full max-w-[28rem] flex-col gap-5">
      {submitted && problems.length > 0 && (
        <Alert
          ref={summary}
          tabIndex={-1}
          role="alert"
          tone="error"
          className="outline-none focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-focus"
          title={problems.length === 1 ? 'One thing to fix before you create the project' : `${problems.length} things to fix before you create the project`}
          description={
            <ul className="m-0 flex flex-col gap-1 p-0">
              {problems.map((f) => (
                <li key={f} className="list-none">
                  <button type="button" onClick={() => focusField(f)} className="cursor-pointer text-start text-body text-fg-strong underline underline-offset-2">
                    {LABELS[f]}: {errors[f]}
                  </button>
                </li>
              ))}
            </ul>
          }
        />
      )}
      <Input ref={name} label={LABELS.name} placeholder="Spring launch" value={values.name} error={errors.name} onChange={(e) => set('name', e.target.value)} />
      <Select ref={owner} label={LABELS.owner} placeholder="Choose a person" options={OWNERS} value={values.owner} error={errors.owner} onChange={(e) => set('owner', e.target.value)} />
      <RadioGroup ref={visibility} label={LABELS.visibility} options={VISIBILITY} value={values.visibility} error={errors.visibility} onValueChange={(v) => set('visibility', v)} />
      <div className="flex flex-wrap gap-3">
        <Button type="submit">Create project</Button>
        <Button variant="ghost" onClick={reset}>Clear</Button>
      </div>
    </form>
  )
}
```

## One message for a group

A rule about a group, such as choose at least one, gets one message under the group instead of one per box. Each box is marked invalid, so it shows the error border and is announced as invalid, and the fieldset links the message.

- Do: Put the rule in the group's hint before anything goes wrong: Pick one or more.
- Avoid: Reveal the rule only as an error after submit.

### Demo: Mention notifications

Press Save preferences with nothing chosen, then tick any box.

```tsx
'use client'
import { useId, useRef, useState, type FormEvent } from 'react'
import { Button } from '@/nacre/components/Button'
import { Checkbox } from '@/nacre/components/Checkbox'

// One message for a group. Each box gets invalid (error border, aria-invalid) without its own text; the fieldset
// links the single message, so a screen reader hears the rule once with the group name. A failed save moves focus to
// the first box, which reads the group name, its invalid state and that message.

const CHANNELS = [
  { id: 'email', label: 'Email', description: 'At most one summary an hour.' },
  { id: 'push', label: 'Push on my phone' },
  { id: 'digest', label: 'Monday digest', description: 'Every mention from last week in one email.' },
]

export function FieldGroup() {
  const id = useId()
  const [on, setOn] = useState<Record<string, boolean>>({})
  const [tried, setTried] = useState(false)
  const [saved, setSaved] = useState('')
  const first = useRef<HTMLInputElement>(null)
  const none = !CHANNELS.some((c) => on[c.id])
  const bad = tried && none
  const submit = (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault()
    setTried(true)
    setSaved(none ? '' : 'Saved. You will hear about mentions the way you chose.')
    if (none) requestAnimationFrame(() => first.current?.focus())
  }
  return (
    <form noValidate onSubmit={submit} className="flex w-full max-w-[24rem] flex-col gap-5">
      <fieldset aria-describedby={`${id}-note`} className="m-0 flex min-w-0 flex-col gap-3 border-0 p-0">
        <legend className="mb-3 p-0 text-label text-fg-strong">When someone mentions you</legend>
        {CHANNELS.map((c, i) => (
          <Checkbox
            key={c.id}
            ref={i === 0 ? first : undefined}
            name="mentions"
            value={c.id}
            label={c.label}
            description={c.description}
            invalid={bad}
            checked={Boolean(on[c.id])}
            onCheckedChange={(v) => { setOn((o) => ({ ...o, [c.id]: v })); setSaved('') }}
          />
        ))}
        <p id={`${id}-note`} data-state={bad ? 'error' : 'hint'} className={`m-0 text-caption ${bad ? 'text-error-strong' : 'text-fg-muted'}`}>
          {bad ? 'Choose at least one way to hear about mentions.' : 'Pick one or more.'}
        </p>
      </fieldset>
      <div className="flex flex-wrap items-center gap-3">
        <Button type="submit">Save preferences</Button>
        <p role="status" className="text-caption text-fg-muted">{saved}</p>
      </div>
    </form>
  )
}
```

## Built with

- [Button](https://enxm.me/services/design-systems/nacre/components/button)
- [Input](https://enxm.me/services/design-systems/nacre/components/input)
- [Select](https://enxm.me/services/design-systems/nacre/components/select)
- [Checkbox](https://enxm.me/services/design-systems/nacre/components/checkbox)
- [Radio](https://enxm.me/services/design-systems/nacre/components/radio)
- [Alert and toast](https://enxm.me/services/design-systems/nacre/components/alert)
