# Field

> The behavior every Salmon input shares - labels, descriptions, errors, sizes, adornments, clearing, form participation, SSR and accessibility - and the public Field wrapper for custom controls.

Canonical: https://salmonui.dev/docs/inputs/field

Every Inputs component renders the same parts: a real `<label for>`, the
control, a description and an error. `label`, `description`,
`errorMessage`, `invalid`, `validation`, `validateOn` and `size` are props of
every field; `Field` is public for custom controls.

```tsx
import { Field } from '@salmonui/inputs/form';
import '@salmonui/inputs/form/styles.css';

<Field name="plan" label="Plan" description="You can change it later" validation={{ required: true }} value={plan}>
  {(field) => <MyControl {...field.inputProps} value={plan} onChange={setPlan} />}
</Field>
```

### Live demo: Field with a custom control

Live demo: https://salmonui.dev/demos/inputs/field-custom

A native select wrapped in Field with a label, a description, a required rule and an error placed next to the control.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Field, FieldError } from '@salmonui/inputs/form';

// A native select wrapped in Field: label, description, rules and a manually placed error.
export default function FieldCustomDemo() {
  const [plan, setPlan] = useState('');
  return (
    <div style={{ display: 'grid', gap: 16, maxWidth: 360 }}>
      <Field name="plan" label="Plan" description="You can change it later" value={plan} validation={{ required: [true, 'Pick a plan'] }} validateOn="change" errorPlacement="manual">
        {(field) => (
          <div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
            <select {...field.inputProps} value={plan} onChange={(event) => setPlan(event.target.value)}>
              <option value="">Choose…</option>
              <option value="free">Free</option>
              <option value="pro">Pro</option>
            </select>
            <FieldError />
          </div>
        )}
      </Field>
    </div>
  );
}
```

`Field` is controlled by its child: pass the control's current `value` so
the rules can check it. Every built-in field is controlled with `value` /
`onValueChange` (or `checked` / `onCheckedChange`) and uncontrolled with
`defaultValue` (or `defaultChecked`).

## Shared behavior

- **Labels and help.** `aria-describedby` lists the
  description and the visible error, `aria-errormessage` points at the error
  and `aria-invalid` is set only while an error is shown.
- **Error state.** `invalid` forces it; validation results set it.
  The root carries `data-invalid` for styling.
- **Placeholder.** Native `placeholder`.
- **Disabled and read-only.** Native `disabled` and
  `readOnly` (so `<fieldset disabled>` works); the root carries
  `data-disabled`.
- **Class names and styles.** `className` and `style` go to the
  root, `classNames` to the parts, every other prop to the native element.
- **Direction.** The inherited `dir` applies; CSS uses logical
  properties only.
- **Locale.** `localeText` overrides every built-in string per
  component (`clear`, `validation*`); the formatting fields (NumberField,
  Slider) take a BCP 47 `locale` (default `'en-US'`; the host locale is
  never read, so server and client agree).
- **Focus.** `ref` is the native element: `focus()`,
  `blur()`, `click()`; native `onFocus` / `onBlur`.
- **Value events.** Native `onChange` plus
  `onValueChange(value, details)`; `value` / `defaultValue` make the field
  controlled or uncontrolled.
- **Forms.** `name` and `form` are native, so `FormData`
  and React 19 `<form action>` see the value; a form reset restores
  `defaultValue`.
- **Clearing.** `clearable` adds a clear button named by
  `localeText.clear`; Escape clears too.
- **Adornments.** `startAdornment` / `endAdornment` take any node.
- **SSR.** Server and client markup are identical; ids come from
  `useId`; browser APIs are touched only after mount.
- **Size.** `size: 'sm' | 'md' | 'lg'` picks one of three fixed
  metric sets (`data-size`); the theme's `density: 'compact'` tightens
  each set (see [Density](https://salmonui.dev/docs/data-grid/appearance#density)).
- **Accessibility.** axe-core runs on every Inputs component in
  light, dark and RTL with errors shown (`npm run test:a11y`); each
  component page has a keyboard table.

### Live demo: Field states

Live demo: https://salmonui.dev/demos/inputs/field-states

The shared field behavior on TextField, NumberField, Slider and Rating - placeholder, disabled, read-only, sizes, RTL, locale and localeText, adornments, clearing, className and style, ref methods, native focus events and controlled versus uncontrolled values.

`Demo.tsx`:

```tsx
'use client';

import { useRef, useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { NumberField } from '@salmonui/inputs/number-field';
import { Rating } from '@salmonui/inputs/rating';
import { Select } from '@salmonui/dropdowns/select';
import { Slider } from '@salmonui/inputs/slider';
import { TextField } from '@salmonui/inputs/text-field';
import { EventLog, useEventLog } from '../../components/demo-kit';

type Size = 'sm' | 'md' | 'lg';
type Locale = 'en-US' | 'de-DE';

// Built-in strings per locale: `localeText` overrides, `locale` formats.
const TEXT = {
  'en-US': { clear: 'Clear name', validationRequired: 'Enter your name.' },
  'de-DE': { clear: 'Name löschen', validationRequired: 'Bitte einen Namen eingeben.' },
} as const;

// The states every field shares: placeholder, disabled, read-only, size,
// direction, locale, adornments, clearing, className / style, ref methods,
// native focus events and controlled vs uncontrolled values.
export default function FieldStatesDemo() {
  const nameRef = useRef<HTMLInputElement>(null);
  const [name, setName] = useState('Ada');
  const [disabled, setDisabled] = useState(false);
  const [readOnly, setReadOnly] = useState(false);
  const [rtl, setRtl] = useState(false);
  const [size, setSize] = useState<Size>('md');
  const [locale, setLocale] = useState<Locale>('en-US');
  const [log, push] = useEventLog(12);
  return (
    <>
      <div className="demo-toolbar">
        <Checkbox checked={disabled} onCheckedChange={(checked) => setDisabled(checked)}>
          disabled
        </Checkbox>
        <Checkbox checked={readOnly} onCheckedChange={(checked) => setReadOnly(checked)}>
          readOnly
        </Checkbox>
        <Checkbox checked={rtl} onCheckedChange={(checked) => setRtl(checked)}>
          dir="rtl"
        </Checkbox>
        <label>
          size
          <Select aria-label="size" data={['sm', 'md', 'lg']} value={size} onValueChange={(value) => value != null && setSize(value as Size)} />
        </label>
        <label>
          locale
          <Select aria-label="locale" data={['en-US', 'de-DE']} value={locale} onValueChange={(value) => value != null && setLocale(value as Locale)} />
        </label>
      </div>
      <div className="demo-toolbar">
        <Button type="button" variant="outline" onClick={() => nameRef.current?.focus()}>
          ref.focus()
        </Button>
        <Button type="button" variant="outline" onClick={() => nameRef.current?.blur()}>
          ref.blur()
        </Button>
        <Button type="button" variant="outline" onClick={() => nameRef.current?.click()}>
          ref.click()
        </Button>
      </div>
      <div dir={rtl ? 'rtl' : 'ltr'} style={{ display: 'grid', gap: 16, maxInlineSize: 380 }}>
        <TextField
          ref={nameRef}
          label="Name (controlled)"
          placeholder="Your name"
          required
          validation={{ required: true }}
          clearable
          localeText={TEXT[locale]}
          startAdornment="@"
          size={size}
          disabled={disabled}
          readOnly={readOnly}
          value={name}
          onValueChange={(value, details) => {
            setName(value);
            push(`onValueChange ${JSON.stringify(value)} (${details.reason}, ${details.source})`);
          }}
          onChange={(event) => push(`onChange: native input event, target.value ${JSON.stringify(event.target.value)}`)}
          onFocus={() => push('onFocus')}
          onBlur={() => push('onBlur')}
          onClick={() => push('onClick')}
          className="demo-accent-field"
          style={{ borderInlineStart: '3px solid var(--salmon-color-primary)', paddingInlineStart: 8 }}
          description="Clear it with the button or Escape: the required rule then shows its localized message."
        />
        <TextField label="Nickname (uncontrolled)" placeholder="Optional" defaultValue="" endAdornment=".dev" size={size} disabled={disabled} readOnly={readOnly} />
        <NumberField label="Budget" locale={locale} currency="EUR" defaultValue={1234.5} size={size} disabled={disabled} readOnly={readOnly} description="Formatted with the chosen locale on blur" />
        <Slider label="Balance" defaultValue={30} fill valueLabel={{ show: 'focus' }} disabled={disabled} readOnly={readOnly} description="Arrow keys follow the direction: in RTL, ArrowLeft increases" />
        <Rating label="Mood" defaultValue={3} disabled={disabled} readOnly={readOnly} size={size} />
      </div>
      <p className="demo-status">Name: {JSON.stringify(name)}</p>
      <EventLog entries={log} label="Field events" />
    </>
  );
}
```

### Live demo: Fields in a form

Live demo: https://salmonui.dev/demos/inputs/field-forms

Uncontrolled text, masked, number, radio, checkbox, switch, range slider, rating and signature fields in a native form - names and values submitted through FormData, a required incomplete mask blocking the submit, and a form reset restoring every default.

`Demo.tsx`:

```tsx
'use client';

import { useState } from 'react';
import { Button } from '@salmonui/buttons/button';
import { Checkbox } from '@salmonui/inputs/checkbox';
import { Form } from '@salmonui/inputs/form';
import { MaskedField } from '@salmonui/inputs/masked-field';
import { NumberField } from '@salmonui/inputs/number-field';
import { Radio, RadioGroup } from '@salmonui/inputs/radio-group';
import { Rating } from '@salmonui/inputs/rating';
import { Select } from '@salmonui/dropdowns/select';
import { SignaturePad } from '@salmonui/inputs/signature-pad';
import { Slider } from '@salmonui/inputs/slider';
import { Switch } from '@salmonui/inputs/switch';
import { TextField } from '@salmonui/inputs/text-field';

/** One line per FormData entry; long data URLs are shortened. */
function entriesOf(form: HTMLFormElement): string[] {
  return Array.from(new FormData(form), ([key, value]) => {
    const text = typeof value === 'string' ? value : `File ${value.name}`;
    return `${key} = ${text.length > 48 ? `${text.slice(0, 40)}… (${text.length} chars)` : JSON.stringify(text)}`;
  });
}

// Every field is uncontrolled inside a native form: names submit through
// FormData (custom-drawn controls through native or hidden inputs) and the
// Reset button restores each defaultValue and clears the shown errors.
export default function FieldFormsDemo() {
  const [submitValue, setSubmitValue] = useState<'raw' | 'masked'>('raw');
  const [entries, setEntries] = useState<readonly string[]>([]);
  const [status, setStatus] = useState('Change some fields, then submit or reset.');
  return (
    <>
      <div className="demo-toolbar">
        <label>
          MaskedField submitValue
          <Select aria-label="MaskedField submitValue" data={['raw', 'masked']} value={submitValue} onValueChange={(value) => value != null && setSubmitValue(value as 'raw' | 'masked')} />
        </label>
      </div>
      <Form
        aria-label="Delivery preferences"
        style={{ display: 'grid', gap: 16, maxInlineSize: 420 }}
        onSubmit={(event) => {
          event.preventDefault();
          setEntries(entriesOf(event.currentTarget));
          setStatus('Submitted: the FormData entries are listed below.');
        }}
        onValidate={({ valid }) => !valid && setStatus('Not submitted: fix the highlighted field.')}
        onReset={() => {
          setEntries([]);
          setStatus('Reset: every field is back to its defaultValue.');
        }}
      >
        <TextField name="name" label="Name" defaultValue="Ada Lovelace" required />
        <MaskedField name="phone" label="Phone" mask="(000) 000-0000" defaultValue="5551234567" required submitValue={submitValue} description="Required: an incomplete number blocks the submit" />
        <NumberField name="parcels" label="Parcels" defaultValue={2} min={1} max={9} />
        <RadioGroup name="slot" label="Delivery slot" defaultValue="am" orientation="horizontal">
          <Radio value="am">Morning</Radio>
          <Radio value="pm">Afternoon</Radio>
        </RadioGroup>
        <Checkbox name="extras" value="gift-wrap" defaultChecked>
          Gift wrap
        </Checkbox>
        <Switch name="notify" value="sms">
          Text me when it ships
        </Switch>
        <Slider name="window" label="Delivery window (hours)" defaultValue={[9, 17]} min={6} max={22} ticks={{ placement: 'after', majorStep: 4 }} />
        <Rating name="priority" label="Priority" defaultValue={2} count={3} />
        <SignaturePad name="signature" label="Signature" description="Optional: submitted as a PNG data URL" height={120} backgroundColor="#ffffff" />
        <div style={{ display: 'flex', gap: 8 }}>
          <Button type="submit" tone="primary">
            Submit
          </Button>
          <Button type="reset" variant="outline">
            Reset
          </Button>
        </div>
      </Form>
      <p className="demo-status" role="status">
        {status}
      </p>
      <pre className="demo-log" aria-label="Submitted FormData">
        {entries.length === 0 ? '(nothing submitted yet)' : entries.join('\n')}
      </pre>
    </>
  );
}
```

### Live demo: Keyboard and screen readers

Live demo: https://salmonui.dev/demos/inputs/inputs-keyboard

Every Inputs control in one tab order with the role, name, value and description the focused element exposes to assistive technology - textbox, masked textbox, spin button, radio group, checkboxes, switch, two-thumb slider, rating and one-time code.

`Demo.tsx`:

```tsx
'use client';

import { useState, type FocusEvent } from 'react';
import { Checkbox, CheckboxGroup } from '@salmonui/inputs/checkbox';
import { MaskedField } from '@salmonui/inputs/masked-field';
import { NumberField } from '@salmonui/inputs/number-field';
import { OtpField } from '@salmonui/inputs/otp-field';
import { Radio, RadioGroup } from '@salmonui/inputs/radio-group';
import { Rating } from '@salmonui/inputs/rating';
import { Slider } from '@salmonui/inputs/slider';
import { Switch } from '@salmonui/inputs/switch';
import { TextField } from '@salmonui/inputs/text-field';

/** The accessible name a screen reader announces, from aria-labelledby, aria-label or the native label. */
function nameOf(el: HTMLElement): string {
  const ids = el.getAttribute('aria-labelledby');
  if (ids) return ids.split(' ').map((id) => document.getElementById(id)?.textContent ?? '').join(' ').trim();
  const label = el.getAttribute('aria-label');
  if (label) return label;
  const input = el as HTMLInputElement;
  return input.labels?.[0]?.textContent?.trim() ?? '';
}

/** What assistive technology reads for the focused control: role, name, state and description. */
function describe(el: HTMLElement): string {
  const input = el as HTMLInputElement;
  const role = el.getAttribute('role') ?? (el.tagName === 'INPUT' ? (input.type === 'text' || input.type === 'search' || input.type === 'password' ? 'textbox' : input.type === 'range' ? 'slider' : input.type) : el.tagName.toLowerCase());
  const parts = [`role ${role}`, `name "${nameOf(el)}"`];
  const valueText = el.getAttribute('aria-valuetext') ?? el.getAttribute('aria-valuenow');
  if (valueText) parts.push(`value "${valueText}"`);
  if (input.type === 'checkbox' || input.type === 'radio') parts.push(input.checked ? 'checked' : 'not checked');
  if (input.maxLength > 0) parts.push(`maxlength ${input.maxLength}`);
  const described = el.getAttribute('aria-describedby');
  if (described) parts.push(`description "${described.split(' ').map((id) => document.getElementById(id)?.textContent ?? '').join(' ').trim()}"`);
  return parts.join(', ');
}

// Every Inputs control in tab order. The read-out shows what the focused
// element exposes to assistive technology, updated on focus and value changes.
export default function InputsKeyboardDemo() {
  const [focused, setFocused] = useState('Press Tab to move into the first field.');
  const update = (event: FocusEvent<HTMLDivElement> | { target: EventTarget | null }) => {
    const target = event.target as HTMLElement | null;
    if (target && target instanceof HTMLElement && target.matches('input, textarea, [role="slider"], [role="spinbutton"]')) setFocused(describe(target));
  };
  return (
    <>
      <div style={{ display: 'grid', gap: 16, maxInlineSize: 420 }} onFocus={update} onKeyUp={(event) => update({ target: document.activeElement })}>
        <TextField label="Full name" description="As on your ID" />
        <MaskedField label="Postcode" mask="00000-000" description="Format 00000-000" />
        <NumberField label="Tip" formatOptions={{ style: 'currency', currency: 'USD' }} defaultValue={12} min={0} max={100} />
        <RadioGroup label="Payment" name="kb-payment" defaultValue="card" orientation="horizontal">
          <Radio value="card">Card</Radio>
          <Radio value="cash">Cash</Radio>
          <Radio value="voucher">Voucher</Radio>
        </RadioGroup>
        <CheckboxGroup label="Extras" name="kb-extras" orientation="horizontal">
          <Checkbox value="napkins">Napkins</Checkbox>
          <Checkbox value="cutlery">Cutlery</Checkbox>
        </CheckboxGroup>
        <Switch>Leave at the door</Switch>
        <Slider label="Spice level" defaultValue={[2, 4]} min={0} max={5} ticks={{ placement: 'after', majorStep: 1 }} />
        <Rating label="Rate the last order" defaultValue={4} />
        <OtpField label="Courier code" length={4} />
      </div>
      <p className="demo-status" role="status" aria-label="Focused control">
        {focused}
      </p>
    </>
  );
}
```

## Design notes

| Behavior | Why | How to |
| --- | --- | --- |
| No floating label: the label is a static `<label>` above the control. | One look per component; a label inside the input is hard to read at zoom and cut off by translations. | Put hints in `placeholder` or `description`. |
| No attribute-bag prop or method. | React props already are the attribute API. | Unknown props spread on the native element (`data-id="x"`, `aria-*`, `inputMode`). |
| No `width` prop. | Sizing belongs to layout CSS. | `style={{ inlineSize: 240 }}` or `className`. |
| No built-in persistence. | Components never write storage; it would break server rendering. | Controlled `value` plus your own storage. |
| No HTML sanitizer option. | No Inputs component renders an HTML string, so there is nothing to sanitize. | Labels and templates are `ReactNode`. |
| No lifecycle events or imperative teardown and refresh methods. | React owns mounting and unmounting. | Effects in your component; `key` to remount. |
| `onChange` fires per edit, like the native `input` event, not on blur. | It matches React and the DOM. | `onBlur` or `onValueCommit` where a component has one. |
| No method that inserts icons into the input. | Imperative DOM insertion breaks React rendering and server markup. | `startAdornment` / `endAdornment`. |
| No warning or success states. | Status colors outside the five seeds; a green border tells a screen reader nothing. | `description` for guidance, error state for problems. |
| No animation option. | The theme has no animation API. | One fixed transition, off under `prefers-reduced-motion`. |

## API

| `Field` prop | Type |
| --- | --- |
| `children` | `(field) => ReactNode`; `field.inputProps` carries `id`, `name`, `required`, `disabled`, ARIA wiring, `ref` and `onBlur` |
| `value` | the control's value, for `validation` |
| `name`, `id`, `required`, `disabled` | forwarded through `inputProps` |
| `label`, `description`, `errorMessage`, `invalid`, `validation`, `validateOn`, `size`, `localeText` | shared field props |
| `errorPlacement` | `'auto' \| 'manual'` (`'manual'` when the children render `FieldError`) |
| `requiredMark` | `boolean`: `true` marks the label while the control is required, `false` opts out under a `Form requiredMark` ([Required marks](https://salmonui.dev/docs/inputs/form#required-marks)) |

`useFieldContext()` returns the enclosing field's state (`errors`,
`invalid`, `validating`, ids); `FieldError` and `FieldDescription` are the
error and description parts for custom layouts.

Full signatures: [`@salmonui/inputs/form` API reference](https://salmonui.dev/docs/reference/inputs/form)
(`Field`, `FieldError`, `FieldDescription`, `useFieldContext`, `FieldCommonProps`).
