Skip to content
View as Markdown

Form, Field, and Fieldset ​

Form, Field, and Fieldset are compound components for building accessible, validated forms. They handle label association, aria-describedby, validation state, and external error routing automatically.

Import ​

tsx
import { Form, Field, Fieldset } from "@tailor-platform/app-shell";

The runnable examples also import useId, useRef, and useState from react, and Button, Combobox, Select, and Text from @tailor-platform/app-shell.

Basic Usage ​

Submit an empty or malformed email to see validation errors, then enter a valid email to see the submitted value. This example keeps the result in local state; nothing is sent to a server. noValidate disables the browser's native validation popup so Field.Error displays the messages.

tsx
function BasicUsage() {
  const [submitted, setSubmitted] = useState<{ email: string } | null>(null);

  return (
    <Form<{ email: string }>
      noValidate
      className="max-w-sm space-y-4"
      onFormSubmit={(values) => setSubmitted(values)}
    >
      <Field.Root name="email">
        <Field.Label>Email</Field.Label>
        <Field.Control type="email" required />
        <Field.Description>We'll never share your email.</Field.Description>
        <Field.Error match="valueMissing">Email is required.</Field.Error>
        <Field.Error match="typeMismatch">Enter a valid email address.</Field.Error>
      </Field.Root>
      <Button type="submit">Save</Button>
      <Text.p role="status">
        {submitted ? `Submitted email: ${submitted.email}` : "No email submitted yet."}
      </Text.p>
    </Form>
  );
}

Form ​

A form element with consolidated error handling and validation. Wraps every child Field.Root in a shared validation context.

Form Props ​

PropTypeDefaultDescription
childrenReact.ReactNodeRequiredForm contents
onFormSubmit(values: FormValues, details: FormSubmitEventDetails) => void-Called after successful validation with parsed form values. Prefer this for simple forms. Use a type argument for type-safe values.
onSubmitReact.FormEventHandler-Low-level native submit handler. Use when integrating with React Hook Form's handleSubmit.
errorsRecord<string, string>-External errors keyed by field name (e.g. from an API response). Automatically routed to matching Field.Error components.
validationMode"onSubmit" | "onBlur" | "onChange""onSubmit"Controls when field validation fires.
noValidateboolean-Disables native browser validation UI (recommended — AppShell renders its own).
actionsRefReact.Ref<{ validate: () => void }>-Ref to imperatively trigger validation from outside the submit flow.
idstring-Applied to the <form> element. Lets a submit button outside the form target it via the native form attribute.
classNamestring-Additional CSS classes for the <form> element.

External Errors ​

Feed API validation errors back into the form via the errors prop. Errors are keyed by field name and cleared automatically when the user edits the corresponding field.

Save the prefilled https://taken.example.com to simulate a server rejection. Editing the URL clears the error; submitting a different valid URL shows a local success result. No network request is made. In an application, replace the simulated response with errors returned by your API.

tsx
function ExternalErrors() {
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [savedUrl, setSavedUrl] = useState<string | null>(null);

  function handleSubmit(values: { url: string }) {
    // Simulate an API validation response without sending a request.
    if (values.url === "https://taken.example.com") {
      setErrors({ url: "This homepage is already registered." });
      setSavedUrl(null);
      return;
    }

    setErrors({});
    setSavedUrl(values.url);
  }

  return (
    <Form<{ url: string }>
      noValidate
      errors={errors}
      onFormSubmit={handleSubmit}
      className="max-w-sm space-y-4"
    >
      <Field.Root name="url">
        <Field.Label>Homepage</Field.Label>
        <Field.Control type="url" required defaultValue="https://taken.example.com" />
        <Field.Description>Try another URL after the simulated server rejection.</Field.Description>
        <Field.Error />
      </Field.Root>
      <Button type="submit">Save homepage</Button>
      <Text.p role="status">
        {savedUrl ? `Saved homepage: ${savedUrl}` : "No homepage saved yet."}
      </Text.p>
    </Form>
  );
}

Programmatic Validation ​

Use actionsRef to imperatively trigger validation (e.g. in a multi-step wizard).

Leave the name empty and click Check to reveal the required-field error, then enter a name and check again. The button sits outside the form and triggers validation without submitting it.

tsx
function ProgrammaticValidation() {
  const actions = useRef<{ validate: () => void }>(null);

  return (
    <div className="max-w-sm space-y-4">
      <Form noValidate actionsRef={actions}>
        <Field.Root name="name">
          <Field.Label>Name</Field.Label>
          <Field.Control required />
          <Field.Error match="valueMissing">Name is required.</Field.Error>
        </Field.Root>
      </Form>
      <Button type="button" variant="outline" onClick={() => actions.current?.validate()}>
        Check
      </Button>
    </div>
  );
}

Field ​

A compound component that groups all parts of a form field and manages its validation state.

Field.Root creates a context boundary. All child sub-components and any Base UI-backed AppShell component (e.g. Select, Combobox, Autocomplete) placed inside Field.Root automatically connect to this context — inheriting label association (htmlFor), aria-describedby, disabled state, and validation state.

Sub-components ​

Sub-componentDescription
Field.RootContext boundary for a single field. Manages validation state.
Field.LabelAccessible label; htmlFor is resolved automatically via context.
Field.ControlStyled text <input>. Select, Combobox, and the other self-wired controls go directly under Field.Root instead.
Field.DescriptionSupplementary help text; automatically linked via aria-describedby.
Field.ErrorValidation error message. Use match to target specific validity states.
Field.ValidityRender-prop access to the field's ValidityState for fully custom validation UI.

Field.Root Props ​

PropTypeDefaultDescription
namestring-Field name; used for form value extraction and error routing.
childrenReact.ReactNode-Field sub-components and input controls.
disabledboolean-Disables all controls within the field.
isTouchedboolean-Whether the field has been blurred. Maps to React Hook Form's fieldState.isTouched.
isDirtyboolean-Whether the field value differs from its default. Maps to React Hook Form's fieldState.isDirty.
invalidboolean-Marks the field as invalid (shows error styling).
error{ message?: string }-Error object from React Hook Form's fieldState.error. Sets invalid automatically when provided.
validate(value: string) => string | undefined-Custom validation function; return an error message string to mark the field invalid.
validationMode"onSubmit" | "onBlur" | "onChange"-Overrides the parent Form's validationMode for this field.
validationDebounceTimenumber-Debounce delay (ms) for "onChange" validation mode.
classNamestring-Additional CSS classes for the field wrapper.

Field.Error Props ​

PropTypeDefaultDescription
matchkeyof ValidityState | boolean | ((value: string) => boolean)-Validity state key to match (e.g. "valueMissing", "typeMismatch"). Omit for a catch-all error message.
childrenReact.ReactNode-Error message content. If omitted, the browser's native validation message is shown.

Using Another AppShell Component as the Control ​

Field.Control is a text input. It is the control for plain text-like fields, and you can pass it a native element such as render={<textarea />}. The controls in the last row of the table below go directly under Field.Root, as a sibling of Field.Label. Each one registers itself with the Field context, so it gets label association, aria-describedby, disabled, and validation state without Field.Control.

ControlWhere it goes
Plain text, email, number, password, … input<Field.Control type="…" />
Native element (<textarea>, <input type="…">)<Field.Control render={<textarea />} />
Select, Combobox, Autocomplete, Checkbox, Textarea, DateField, DatePicker, DateRangePicker (and their .Async), Tree (checkbox mode)Directly under Field.Root — not Field.Control

Input is the exception. It is a plain <input> that does not connect to Field.Root, so inside a field use <Field.Control /> in its place.

Do not pass the self-wired controls to Field.Control's render prop. They draw their own frame, so <Field.Control render={<Select />} /> renders a second border around the select. Field.Control also passes them <input> props they don't take. Field.Control logs a console warning when it is given one of these controls directly as an element. A wrapper component or the function form of render is not detected.

Submit without choosing a country to see the required-field error, then choose one and submit again to inspect the values. The Select needs no name, value, or onValueChange of its own: Field.Root handles registration, and the only React state stores the submitted result.

tsx
function WithSelect() {
  const [submitted, setSubmitted] = useState<{ country: string } | null>(null);

  return (
    <Form<{ country: string }>
      noValidate
      className="max-w-sm space-y-4"
      onFormSubmit={(values) => setSubmitted(values)}
    >
      <Field.Root name="country">
        <Field.Label>Country</Field.Label>
        <Select items={["Japan", "United States"]} placeholder="Select a country" required />
        <Field.Description>The field supplies the label and submitted name.</Field.Description>
        <Field.Error match="valueMissing">Please select a country.</Field.Error>
      </Field.Root>
      <Button type="submit">Submit country</Button>
      <pre role="status" className="overflow-x-auto text-sm">
        {submitted ? JSON.stringify(submitted, null, 2) : "No country submitted yet."}
      </pre>
    </Form>
  );
}

How values reach onFormSubmit ​

onFormSubmit does not read FormData. It collects values from the Field.Roots registered inside the Form, keyed by each field's name. Every AppShell control works this way once wrapped in a Field.Root — Select, Combobox, and Autocomplete included. They need no name of their own and usually no React state. Mirroring a field into useState just to submit it is normally an anti-pattern; the exception is a value the component must read during render, such as a composer body that gates the submit button or swaps its placeholder.

Non-string items are serialised into the submitted value:

Item shapeValue in onFormSubmit
stringthe string
{ value, label }value, automatically
any other objectJSON string — usually not wanted
any other object + itemToStringValuewhatever that function returns

Multi-select submits an array. For arbitrary objects, pass itemToStringValue to choose what gets submitted — it is distinct from mapItem, which controls what the user sees:

Choose a warehouse and submit to inspect the JSON result. For example, Tokyo warehouse is displayed as a name but submitted as { "warehouse": "1" } — not the whole object. Selection remains owned by the field; the example keeps only fixture data and the submitted result in React state.

tsx
function SubmittedValues() {
  const [warehouses] = useState([
    { id: 1, name: "Tokyo warehouse" },
    { id: 2, name: "Osaka warehouse" },
  ]);
  const [submitted, setSubmitted] = useState<{ warehouse: string } | null>(null);

  return (
    <Form<{ warehouse: string }>
      noValidate
      className="max-w-sm space-y-4"
      onFormSubmit={(values) => setSubmitted(values)}
    >
      <Field.Root name="warehouse">
        <Field.Label>Warehouse</Field.Label>
        <Combobox
          items={warehouses}
          mapItem={(warehouse) => ({ label: warehouse.name, key: String(warehouse.id) })}
          itemToStringValue={(warehouse) => String(warehouse.id)}
          placeholder="Select a warehouse"
          required
        />
        <Field.Description>
          The warehouse name is displayed, but its ID is submitted.
        </Field.Description>
        <Field.Error match="valueMissing">Please select a warehouse.</Field.Error>
      </Field.Root>
      <Button type="submit">Submit warehouse</Button>
      <pre role="status" className="overflow-x-auto text-sm">
        {submitted ? JSON.stringify(submitted, null, 2) : "No warehouse submitted yet."}
      </pre>
    </Form>
  );
}

Composer-style textareas ​

Most forms should let Field.Root own the submitted value. A composer is the notable exception: the current draft is often read during render to disable Send on whitespace-only input, swap the placeholder, or show live UI around the text. In that case, keep the Textarea controlled, but still make it a real field inside Form so validation and server errors land beside the draft.

Use a visually hidden Field.Label rather than only aria-label so the field keeps the same label, description, and error wiring as any other form control. If the submit can fail, route the server rejection through Form's errors prop and clear the draft only after success.

tsx
function ReplyComposer() {
  const [body, setBody] = React.useState("");
  const [internal, setInternal] = React.useState(false);
  const [errors, setErrors] = React.useState<Record<string, string>>({});

  async function handleSubmit() {
    const result = await saveReply({ body, internal });
    if (result?.error) {
      setErrors({ body: result.error });
      return;
    }

    setErrors({});
    setBody("");
  }

  return (
    <Form noValidate errors={errors} onFormSubmit={handleSubmit}>
      <Field.Root name="body">
        <Field.Label className="sr-only">Reply</Field.Label>
        <Textarea
          required
          rows={4}
          value={body}
          onChange={(event) => setBody(event.target.value)}
          placeholder={internal ? "Internal context for teammates..." : "Reply to customer..."}
        />
        <Field.Error />
      </Field.Root>

      <Checkbox
        label="Internal note (not sent to customer)"
        checked={internal}
        onCheckedChange={setInternal}
      />

      <Button type="submit" disabled={body.trim().length === 0}>
        Send
      </Button>
    </Form>
  );
}

Native form submission ​

Separately from onFormSubmit, controls can participate in native submission — a plain <form>, new FormData(form), or a server action. That path reads the DOM, so each control needs its own name. Select, Combobox, and Autocomplete accept name (plus form, required, inputRef) from 1.13.0; before that they contributed nothing to a native payload.

Submitting from outside the form ​

Give the Form an id and point a detached submit button at it with the native form attribute — this is how a page-header Save reaches a form in the page body (1.13.0+).

Here Save product is outside the form. Click it with an empty product name to see validation, then enter a name and click again to see the submitted values. useId keeps the association unique if multiple instances are rendered. No layout component or custom click handler is required.

tsx
function ExternalSubmit() {
  const formId = useId();
  const [submitted, setSubmitted] = useState<{ productName: string } | null>(null);

  return (
    <div className="max-w-sm space-y-4">
      <Button type="submit" form={formId}>
        Save product
      </Button>
      <Form<{ productName: string }>
        id={formId}
        noValidate
        onFormSubmit={(values) => setSubmitted(values)}
      >
        <Field.Root name="productName">
          <Field.Label>Product name</Field.Label>
          <Field.Control required />
          <Field.Error match="valueMissing">Product name is required.</Field.Error>
        </Field.Root>
      </Form>
      <pre role="status" className="overflow-x-auto text-sm">
        {submitted ? JSON.stringify(submitted, null, 2) : "No product submitted yet."}
      </pre>
    </div>
  );
}

Custom Validation UI with Field.Validity ​

Field.Validity exposes the field's ValidityState via a render callback, enabling fully custom validation UI.

tsx
function CustomValidation() {
  return (
    <Field.Root name="password" validationMode="onChange">
      <Field.Label>Password</Field.Label>
      <Field.Control type="password" required minLength={8} />
      <Field.Validity>
        {(state) => (
          <ul>
            <li>{state.validity.valueMissing ? "❌" : "✅"} Required</li>
            <li>{state.validity.tooShort ? "❌" : "✅"} At least 8 characters</li>
          </ul>
        )}
      </Field.Validity>
    </Field.Root>
  );
}

Fieldset ​

A compound component (Fieldset.Root, Fieldset.Legend) for grouping related fields with a shared legend for accessible form sectioning.

Sub-components ​

Sub-componentDescription
Fieldset.RootRenders a <fieldset>. Propagates disabled to all children.
Fieldset.LegendAccessible <legend> for the group.

Fieldset.Root Props ​

PropTypeDefaultDescription
childrenReact.ReactNode-Field components to group.
disabledboolean-Disables all controls within the fieldset.
classNamestring-Additional CSS classes.

Example ​

tsx
function BillingFieldset() {
  return (
    <Fieldset.Root>
      <Fieldset.Legend>Billing details</Fieldset.Legend>
      <Field.Root name="company">
        <Field.Label>Company</Field.Label>
        <Field.Control />
      </Field.Root>
      <Field.Root name="taxId">
        <Field.Label>Tax ID</Field.Label>
        <Field.Control />
      </Field.Root>
    </Fieldset.Root>
  );
}

React Hook Form Integration ​

React Hook Form is optional and not an AppShell dependency — install it in your own app. Form + Field is the default stack and covers most forms via onFormSubmit. Reach for RHF only when a form genuinely needs cross-field validation, field arrays, or a schema resolver (Zod). The two compose rather than compete: Field handles accessibility wiring and visual state, RHF handles values and the validation lifecycle.

Field.Root accepts isTouched, isDirty, invalid, and error props that align with React Hook Form's fieldState shape, so you can spread fieldState directly. Use Form's onSubmit prop to connect RHF's handleSubmit.

tsx
import { useForm, Controller } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { z } from "zod";

const schema = z.object({ email: z.string().email() });

function MyForm() {
  const { control, handleSubmit } = useForm({
    resolver: zodResolver(schema),
  });

  return (
    <Form onSubmit={handleSubmit((data) => save(data))}>
      <Controller
        name="email"
        control={control}
        render={({ field, fieldState }) => (
          <Field.Root {...fieldState}>
            <Field.Label>Email</Field.Label>
            <Field.Control {...field} type="email" />
            <Field.Error>{fieldState.error?.message}</Field.Error>
          </Field.Root>
        )}
      />
      <button type="submit">Save</button>
    </Form>
  );
}

The Field context handles only accessibility wiring (htmlFor, aria-describedby) and visual state (data-invalid, data-dirty, data-touched) — it does not interfere with RHF's value management or validation lifecycle.


  • Testing — Role-based field interactions, form submission, and validation tests.
  • Input — Standalone styled input, useful outside of forms.
  • Textarea — Multi-line text control that integrates automatically with Field.
  • Checkbox — Boolean control that integrates automatically with Field.
  • Select — Dropdown that integrates automatically with Field.
  • Combobox — Searchable combobox that integrates automatically with Field.
  • Autocomplete — Free-text input with suggestions that integrates automatically with Field.