# Field

> Form field for React and shadcn: a label, a control and one message line where help text and errors swap in place.

A label, a control and one message line on Base UI Field, where the description and the error swap in place with y + blur. Inside Base UI's Form, submitting focuses the first invalid field.

- Tier: Free (MIT)
- Interaction: Type
- Page: https://eased.dev/components/field
- Registry: https://eased.dev/r/field.json

## Install

```bash
npx shadcn add https://eased.dev/r/field.json
```

A label, one control and one message line on Base UI's Field, which wires the ids, `aria-describedby` and validation between them.

## When to use

- Any labelled form control that can carry help text or an error: an email address, a password, a verification code.
- Forms validated on the client with `validate`, by the browser (`required`, `type="email"`), or by the server through Base UI's `<Form errors>`.
- Wrapping Eased's text controls ([Input](/components/input), [Textarea](/components/textarea), [OTP Field](/components/otp-field)) so their invalid border and shake follow the field.

## When not to use

- A control that names itself, such as a [Checkbox](/components/checkbox) or [Switch](/components/switch) with its own label: they do not need the extra label line.
- A search box in a toolbar with no visible label: give the control an `aria-label` instead.

## Usage

```tsx sign-up.tsx
import { Form } from "@base-ui/react/form";
import { Field } from "@/components/eased/field/field";
import { Input } from "@/components/eased/input/input";

const checkEmail = (value: unknown) =>
  /@(gmail|yahoo|hotmail)\./i.test(String(value)) ? "Use your work email, not a personal one." : null;

export function SignUp({ serverErrors, submit }) {
  return (
    <Form errors={serverErrors} onFormSubmit={submit}>
      <Field name="email" label="Work email" description="We’ll send a sign-in link." validate={checkEmail}>
        <Input type="email" autoComplete="email" />
      </Field>
    </Form>
  );
}
```

## Examples

### An error you control

Pass `error` when the message comes from somewhere else, such as a form library or a server reply. Setting it marks the field invalid; clear it when the person edits.

```tsx
<Field label="Workspace URL" error={taken ? "That URL is already in use." : undefined}>
  <Input value={slug} onChange={(e) => setSlug(e.target.value)} />
</Field>
```

### Validate on blur

Base UI validates on submit by default, then again on every change. Set `validationMode` to check earlier.

```tsx
<Field name="password" label="Password" description="At least 8 characters." validationMode="onBlur" validate={checkPassword}>
  <Input type="password" autoComplete="new-password" />
</Field>
```

## API reference

### Field

| Prop | Type | Default | Description |
|---|---|---|---|
| `label` | `ReactNode` | | The visible label, tied to the control for you. |
| `description` | `ReactNode` | | Helper text under the control. While the field is invalid the error takes its place. |
| `error` | `ReactNode` | | An error you control. Setting it marks the field invalid. Leave it out to show the message from `validate`, `<Form errors>` or the browser. |
| `invalid` | `boolean` | | Marks the field invalid; overrides the state `error` sets. |
| `children` | `ReactNode` | | One control: Input, Textarea, OTP Field or any Base UI control. |

Every other Base UI `Field.Root` prop passes through: `name`, `validate`, `validationMode`, `validationDebounceTime`, `disabled`, `dirty`, `touched`, `actionsRef`, `className`, `render`.

### FieldRoot, FieldLabel and FieldMessage

The parts `Field` is made of, exported for custom layouts. `FieldRoot` is Base UI's `Field.Root` with a 6px rhythm between its parts. `FieldLabel` is `Field.Label`. `FieldMessage` takes `description`, `error` and `className`, and must sit inside a `FieldRoot`.

## Accessibility

- Base UI ties the label to the control and points `aria-describedby` at the description and error.
- The message line sits in a polite live region, so a new error is announced without moving focus.
- Inside Base UI's `<Form>`, submitting with errors moves focus to the first invalid control.
- Errors carry an icon and the danger colour as well as the shake, so motion is never the only signal.

## Motion

The description and the error share one line and swap in place: the outgoing line lifts 3px and blurs out in 100ms, the incoming one rises from 4px below on the snappy spring while its blur and opacity clear over 200ms. When the line count changes, or an error opens the line from nothing, its height springs on the smooth spring; in that last case it waits 80ms so the control's 6px shake lands first. A new message replaces an old one the same way. Reduced motion swaps by opacity alone in 100ms and snaps the height.

## Notes for AI

Wrap every labelled text control in a Field and pass `label` and `description` here rather than on the control. Use `validate` or Base UI's `<Form errors>` for messages, and `error` only when the message comes from outside Base UI.

Do not render your own error paragraph, `aria-describedby` or `aria-live` region, and do not add a second label: the Field already wires them. Keep one control per Field.

## Related

- [Input](/components/input): the text control it usually wraps.
- [Textarea](/components/textarea): for longer text.
- [Label](/components/label): a standalone label when you do not need the message line.

## Example

`components/eased/field/field-demo.tsx`

```tsx
"use client";

import { Form } from "@base-ui/react/form";
import { useEffect, useRef, useState } from "react";
import { Button } from "../button/button";
import { Input } from "../input/input";
import { DemoFrame } from "../lib/demo-frame";
import { Field } from "./field";

const TAKEN = "maya@northwind.com";

const validateEmail = (value: unknown) => {
  const v = String(value ?? "").trim();
  if (!v) return "Enter your work email.";
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)) return "That doesn’t look like an email address.";
  if (/@(gmail|yahoo|hotmail|outlook)\./i.test(v)) return "Use your work email, not a personal one.";
  return null;
};

const validatePassword = (value: unknown) => {
  const v = String(value ?? "");
  if (!v) return "Choose a password.";
  if (v.length < 8) return `Add ${8 - v.length} more character${8 - v.length === 1 ? "" : "s"}.`;
  return null;
};

export function FieldDemo() {
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [state, setState] = useState<"idle" | "loading" | "done">("idle");
  const timer = useRef(0);
  useEffect(() => () => clearTimeout(timer.current), []);

  const submit = (values: Record<string, unknown>) => {
    setState("loading");
    timer.current = window.setTimeout(() => {
      // A server reply: Base UI's Form routes it to the field and focuses it.
      if (String(values.email).trim().toLowerCase() === TAKEN) {
        setErrors({ email: "An account with this email already exists." });
        setState("idle");
        return;
      }
      setState("done");
    }, 900);
  };

  return (
    <DemoFrame title="Create your account" meta="Step 1 of 2">
      <Form
        errors={errors}
        onFormSubmit={submit}
        className="flex min-h-0 flex-1 flex-col gap-4 p-4"
        aria-label="Create your account"
      >
        <Field
          name="email"
          label="Work email"
          description={`We’ll send a sign-in link here. Try ${TAKEN}.`}
          validate={validateEmail}
          onChange={() => errors.email && setErrors({})}
        >
          <Input type="email" placeholder="you@company.com" autoComplete="email" aria-required />
        </Field>

        <Field name="password" label="Password" description="At least 8 characters." validate={validatePassword}>
          <Input type="password" placeholder="••••••••" autoComplete="new-password" aria-required />
        </Field>

        <div className="mt-auto flex items-center justify-between gap-3">
          <p className="text-ui-sm text-text-muted">
            Already have an account?{" "}
            <a href="#" className="rounded-control-2xs text-text underline-offset-2 hover-fine:underline focus-ring">
              Sign in
            </a>
          </p>
          <Button
            type="submit"
            variant="primary"
            loading={state === "loading"}
            disabled={state === "done"}
            focusableWhenDisabled
            swapKey={state === "done" ? "done" : "idle"}
          >
            {state === "done" ? (
              <>
                <svg viewBox="0 0 16 16" fill="none" aria-hidden>
                  <path d="m3.75 8.5 2.75 2.75 5.75-6.5" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
                </svg>
                Account created
              </>
            ) : (
              "Continue"
            )}
          </Button>
        </div>
        <span role="status" className="sr-only">
          {state === "done" ? "Account created" : ""}
        </span>
      </Form>
    </DemoFrame>
  );
}
```
