Talisman LogoTalisman Logo Design System
Browse documentation
Components

Form

Field composition for React Hook Form that lays out label, control, description and error message, and wires their accessibility attributes.

Stableimport { Form } from "@repo/ui/form";Source

Número único do CNJ, com pontos e hífen.

Opcional. Até 200 caracteres.

Press “Cadastrar processo” with the form empty to see the validation messages.

When to use

  • For every form that validates input: React Hook Form owns the state and Zod the rules.
  • To get consistent spacing, labels, descriptions and error messages across forms.

When not to use

  • A single field with no validation, such as a search box. Use Input on its own.
  • Forms that do not use React Hook Form. The parts read the form from context, so they only work inside Form.
  • Settings that apply on change. Use Switch or Checkbox without a form.

Anatomy

Form is React Hook Form’s FormProvider. Spread the object returned by useForm() into it. Each field is a FormField that renders a FormItem.

Part Role
Form Provides the form to every part below. Spread {...form} into it.
FormField Connects one field by name and passes field and fieldState to render.
FormItem Groups label, control and messages, and generates the ids that link them.
FormLabel The field name, linked to the control. required adds an asterisk.
FormControl Wraps the control and sets its id, aria-invalid and aria-describedby.
FormDescription Helper text under the control.
FormMessage The validation error from the schema. Renders nothing when there is no error.

Examples

Form with validation

Rules come from a Zod schema through zodResolver. The Input gets variant="error" from fieldState.error, so the border and the message agree.

Número único do CNJ, com pontos e hífen.

Opcional. Até 200 caracteres.

Showing errors

The same form, validated as it appears. Each FormMessage shows the message from the schema, and FormControl marks the control aria-invalid.

Número único do CNJ, com pontos e hífen.

Opcional. Até 200 caracteres.

Content

  • Write messages as the fix, not the problem: “Informe o número do processo.”, “Use o formato NNNNNNN-DD.AAAA.J.TR.OOOO.”
  • Mark required fields with required on FormLabel and leave optional ones unmarked, adding “Opcional” to the description.
  • Use FormDescription for rules the user needs before typing, and FormMessage for what went wrong.
  • Name the submit button after the result: “Cadastrar processo”, not “Enviar”.

Accessibility

  • FormItem generates one id and derives formItemId, the description id and the message id from it, so FormLabel (htmlFor), FormDescription and FormMessage always point at the right control.
  • FormControl sets id, aria-invalid and aria-describedby on its child with Radix Slot. The child must be a single element that accepts them: Input, Textarea, Checkbox.
  • Add noValidate to the <form> and let Zod produce the messages, so the browser does not show its own tooltips.
  • Errors are text next to the field, not color alone. FormMessage is not a live region, so move focus to the first invalid field on submit failure. React Hook Form does this by default through shouldFocusError.
  • Controls that wrap their own label or message, such as Input with the label prop, duplicate what FormLabel and FormMessage already provide. Use the bare control.

Code

import { zodResolver } from "@hookform/resolvers/zod";
import { useForm } from "react-hook-form";
import { z } from "zod";
import {
  Form,
  FormControl,
  FormDescription,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@repo/ui/form";
import { Input } from "@repo/ui/input";

const schema = z.object({
  caseNumber: z.string().min(1, "Informe o número do processo."),
});

const form = useForm({
  defaultValues: { caseNumber: "" },
  resolver: zodResolver(schema),
});

<Form {...form}>
  <form noValidate onSubmit={form.handleSubmit(onSubmit)}>
    <FormField
      control={form.control}
      name="caseNumber"
      render={({ field, fieldState }) => (
        <FormItem>
          <FormLabel required>Número do processo</FormLabel>
          <FormControl>
            <Input
              {...field}
              variant={fieldState.error ? "error" : "default"}
            />
          </FormControl>
          <FormDescription>Número único do CNJ.</FormDescription>
          <FormMessage />
        </FormItem>
      )}
    />
  </form>
</Form>;

Props

Form is FormProvider from React Hook Form and takes the return value of useForm().

Form
PropTypeDefaultDescription
controlControl—Not needed: `Form` spreads the `useForm()` return value
handleSubmitUseFormHandleSubmit—From `useForm()`. Wrap your submit handler with it
FormField
PropTypeDefaultDescription
controlControl—The `control` from `useForm()`.
nameFieldPath—Field name. Must match a key of the schema.
render({ field, fieldState, formState }) => ReactElement—Renders the field. Spread `field` on the control.
defaultValue, rules, shouldUnregisterControllerProps—Passed to React Hook Form's `Controller`.
FormLabel
PropTypeDefaultDescription
requiredbooleanfalseAdds a red asterisk after the label.
size"lg" | "md" | "sm" | "xs" | "xxs""sm"Type size, as in Label.
forstring—Overrides the generated control id. Rarely needed.
FormMessage
PropTypeDefaultDescription
childrenReactNode—Text shown when there is no error. The error message wins when there is one.

FormItem takes native div attributes. FormControl takes the single child that receives the accessibility attributes. FormDescription takes native p attributes and renders Typography at paragraphXs.

Known issues

Issue Effect
FormControl always lists the description id in aria-describedby, even without a FormDescription. The attribute points at an id that does not exist, which some validators flag.
FormMessage is not a live region. Screen readers do not announce a new error when it appears, unless focus moves to the field.
useFormField checks !fieldContext, but the context default is {}, so it never throws. Using FormLabel outside FormField fails later with a confusing React Hook Form error.
FormControl does not set the control’s variant. Input and Textarea only turn red when you pass variant="error" yourself, as in the examples above.
Edit this page on GitHub