# Field
A label, control, help text and error, wired and validated.
Source page: https://dinachi.dev/docs/components/field

## Installation
```bash
npx @dinachi/cli@latest add field
```
Adds to your project:
- `components/ui/field/field.tsx`
- `components/ui/field/index.ts`
Installs:
- `@base-ui/react` ^1.9.0

## Usage
```tsx
import {
  Field,
  FieldControl,
  FieldDescription,
  FieldError,
  FieldLabel,
} from "@/components/ui/field"

export function EmailField() {
  return (
    <Field name="email">
      <FieldLabel>Email</FieldLabel>
      <FieldControl type="email" required />
      <FieldDescription>We only use it to sign you in.</FieldDescription>
      <FieldError />
    </Field>
  )
}
```

## Anatomy
```tsx
<Field>
  <FieldLabel />
  <FieldControl />
  <FieldDescription />
  <FieldError />
  <FieldValidity />
</Field>
```
- `Field`: Holds the field's name, state and validation.
- `FieldLabel`: The visible label, linked to the control.
- `FieldControl`: The input, wired to the field.
- `FieldDescription`: Help text, linked to the control.
- `FieldError`: The error, shown while invalid.
- `FieldValidity`: Renders from the field's validity state.

## Examples

### Default
Label, control and description.
```tsx
import { Field, FieldLabel, FieldControl, FieldDescription } from '@/components/ui/field';

export function Example() {
  return (
    <Field className="w-full max-w-sm">
      <FieldLabel>Email</FieldLabel>
      <FieldControl type="email" placeholder="Enter your email" />
      <FieldDescription>We'll never share your email.</FieldDescription>
    </Field>
  );
}
```

### Validation
Validate as you type after the first blur.
```tsx
import { Field, FieldLabel, FieldControl, FieldDescription, FieldError } from '@/components/ui/field';
import { useState } from 'react';

export function Example() {
  const [value, setValue] = useState('');
  const [touched, setTouched] = useState(false);

  const isValid = value.length >= 3;
  const showError = touched && !isValid;

  return (
    <Field invalid={showError} className="w-full max-w-sm">
      <FieldLabel>Username</FieldLabel>
      <FieldControl
        value={value}
        onChange={(e) => setValue(e.target.value)}
        onBlur={() => setTouched(true)}
        placeholder="Enter username"
      />
      <FieldDescription>Must be at least 3 characters.</FieldDescription>
      {showError && <FieldError>Username must be at least 3 characters</FieldError>}
    </Field>
  );
}
```

### Error
An invalid field with its message.
```tsx
import { Field, FieldLabel, FieldControl, FieldError } from '@/components/ui/field';

export function Example() {
  return (
    <Field invalid className="w-full max-w-sm">
      <FieldLabel>Password</FieldLabel>
      <FieldControl type="password" placeholder="Enter password" />
      <FieldError>Password is required</FieldError>
    </Field>
  );
}
```

### Required
Required controls with a visible marker.
```tsx
import { Field, FieldLabel, FieldControl, FieldDescription } from '@/components/ui/field';

export function Example() {
  return (
    <div className="space-y-4 w-full max-w-sm">
      <Field className="w-full">
        <FieldLabel>
          Full Name <span className="text-destructive">*</span>
        </FieldLabel>
        <FieldControl placeholder="Enter your full name" required />
        <FieldDescription>Your legal name as it appears on documents.</FieldDescription>
      </Field>

      <Field className="w-full">
        <FieldLabel>
          Phone Number <span className="text-destructive">*</span>
        </FieldLabel>
        <FieldControl type="tel" placeholder="+1 (555) 000-0000" required />
        <FieldDescription>We'll use this for account recovery.</FieldDescription>
      </Field>
    </div>
  );
}
```

### Disabled
Disable the whole field from its root.
```tsx
import { Field, FieldLabel, FieldControl, FieldDescription } from '@/components/ui/field';

export function Example() {
  return (
    <Field disabled className="w-full max-w-sm">
      <FieldLabel>Account ID</FieldLabel>
      <FieldControl value="ACC-12345-ABCDE" readOnly />
      <FieldDescription>This field cannot be modified.</FieldDescription>
    </Field>
  );
}
```

## Notes

### Required fields
Put `required` on `FieldControl`. It shows nothing visually; mark the label too.

### Server errors
Inside a [Form](/docs/components/form), pass `errors` keyed by each Field's `name`. Each error clears once its control changes.

## API reference

### Field
Holds the field's name, state and validation.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `name` | `string` | - | Names the field on submit and keys its server errors. |
| `validate` | `(value, formValues) => string \| string[] \| null` | - | Returns an error message, or nothing when valid. May be async. |
| `validationMode` | `"onSubmit" \| "onBlur" \| "onChange"` | `"onSubmit"` | When validate runs. Wins over the Form's setting. |
| `validationDebounceTime` | `number` | `0` | Milliseconds between validate calls in `onChange` mode. |
| `invalid` **agent** | `boolean` | - | Marks the field invalid, for example from a form library. |
| `disabled` **agent** | `boolean` | `false` | Disables the control. Overrides the control's own disabled. |

### FieldLabel
The visible label, linked to the control.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `children` **agent** | `ReactNode` | - | Also the name the agent reads for the control. |

### FieldControl
The input, wired to the field.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `type` | `string` | `"text"` | Any native input type. |
| `value` | `string` | - | Controlled value. |
| `defaultValue` | `string` | - | Starting value when uncontrolled. |
| `onValueChange` | `(value, details) => void` | - | Runs with the new string on each change. |
| `required` **agent** | `boolean` | `false` | Must have a value to be valid. |
| `render` | `ReactElement` | - | Swap the element, keep the wiring. |

### FieldDescription
Help text, linked to the control.

Takes the props of the element it renders.

### FieldError
The error, shown while invalid.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `match` | `boolean \| keyof ValidityState` | - | Shows only for one validity failure, such as `valueMissing`. `true` always shows. |
| `children` **agent** | `ReactNode` | - | The message. Defaults to the browser's or validate's message. The agent reads it as the control's error. |

### FieldValidity
Renders from the field's validity state.

| Prop | Type | Default | Description |
| --- | --- | --- | --- |
| `children` | `(state) => ReactNode` | - | Receives the validity state and the current value. |

## Accessibility
- `FieldLabel` labels the control; clicking it focuses the input.
- `FieldDescription` and `FieldError` describe the control via aria-describedby.
- Invalid controls get aria-invalid and `data-invalid`.
- While invalid, the agent reads `FieldError`'s text as the control's `errors`.

## Source
`components/ui/field/field.tsx`
```tsx
import * as React from "react";
import { Field as BaseField } from "@base-ui/react/field";
import { cn } from "@/lib/utils";

const Field = React.forwardRef<
  HTMLDivElement,
  React.ComponentProps<typeof BaseField.Root>
>(({ className, ...props }, ref) => (
  <BaseField.Root ref={ref} data-slot="field" className={cn("space-y-2", className)} {...props} />
));
Field.displayName = "Field";

const FieldLabel = React.forwardRef<
  HTMLLabelElement,
  React.ComponentProps<typeof BaseField.Label>
>(({ className, ...props }, ref) => (
  <BaseField.Label
    ref={ref}
    data-slot="field-label"
    className={cn(
      "text-sm font-medium leading-none data-[disabled]:cursor-not-allowed data-[disabled]:opacity-70",
      "data-[invalid]:text-destructive",
      className
    )}
    {...props}
  />
));
FieldLabel.displayName = "FieldLabel";

const FieldControl = React.forwardRef<
  HTMLInputElement,
  React.ComponentProps<typeof BaseField.Control>
>(({ className, ...props }, ref) => (
  <BaseField.Control
    ref={ref}
    data-slot="field-control"
    className={cn(
      "flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background",
      "file:border-0 file:bg-transparent file:text-sm file:font-medium",
      "placeholder:text-muted-foreground",
      "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
      "data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50",
      "data-[invalid]:border-destructive data-[invalid]:ring-destructive",
      className
    )}
    {...props}
  />
));
FieldControl.displayName = "FieldControl";

const FieldDescription = React.forwardRef<
  HTMLParagraphElement,
  React.ComponentProps<typeof BaseField.Description>
>(({ className, ...props }, ref) => (
  <BaseField.Description
    ref={ref}
    data-slot="field-description"
    className={cn(
      "text-sm text-muted-foreground",
      "data-[disabled]:opacity-50",
      className
    )}
    {...props}
  />
));
FieldDescription.displayName = "FieldDescription";

const FieldError = React.forwardRef<
  HTMLDivElement,
  React.ComponentProps<typeof BaseField.Error>
>(({ className, ...props }, ref) => (
  // Tells the agent bridge this describes what is wrong, not what the field is for.
  <BaseField.Error
    ref={ref}
    data-slot="field-error"
    data-agent-error=""
    className={cn(
      "text-sm font-medium text-destructive",
      "data-[disabled]:opacity-50",
      className
    )}
    {...props}
  />
));
FieldError.displayName = "FieldError";

const FieldValidity: React.FC<React.ComponentProps<typeof BaseField.Validity>> = (props) => (
  <BaseField.Validity {...props} />
);
FieldValidity.displayName = "FieldValidity";

export {
  Field,
  FieldLabel,
  FieldControl,
  FieldDescription,
  FieldError,
  FieldValidity,
};
```
