# Field Properties

All input components in UI Kit (`TextInput`, `Select`, `ComboBox`, `Checkbox`, `RadioGroup`, `NumberInput`, `Switch`, `DatePicker`, `Slider`, `FileInput`, etc.) share a common set of field properties. These properties are provided by the `FieldBaseProps` interface and enable form integration, validation, labeling, and state management.

When used inside a [Form](./components/form/Form.md), these properties are automatically inherited from the form context and can be overridden at the field level. For the state a form passes down (`isDisabled`, `isReadOnly`, `isInvalid` and `isValid`), a field prop set to `undefined` counts as not set, so a wrapper that passes an optional `isDisabled` through keeps the form's state.

For modern forms, follow the [use-case guide](./components/form/ModernForm.md). Bind with `name` and put validation options on the input, or choose `field={form.field(path, options)}` for model-aware type checking and validator inference. Keep presentation props on the input. These binding styles are alternatives; descriptors are not required for nested data.

## Identity & Form Integration

- **`field`** `FormField<Value>` — Typed modern binding created by `form.field(path, options)`. Supports nested paths and takes precedence over `form` and `name`. Built-in bindings accept `null` and `undefined` alongside their normal model value; display fallbacks do not replace stored nulls.
- **`name`** `string | readonly (string | number)[]` — Field name when a descriptor is not supplied. Modern forms accept literal strings or nested tuple paths, such as `['users', 0, 'email']`. Legacy forms accept strings only and retain dot notation.
- **`form`** `CubeFormInstance | FormController<T>` — Legacy instance or modern controller. Automatically provided when inside a Form context. Pass it explicitly to link an input to a form it is not nested in, or to override the surrounding form.
- **`defaultValue`** `any` — Initial field value. Modern controller values/defaults take precedence, including explicit `null` and `undefined`.
- **`preserve`** `boolean` (modern default: `true`) — Retain the value after the last input for this field unmounts.
- **`isEqual`** `(previous, next) => boolean` — Modern field dirty-value comparator.
- **`id`** `string` — Unique ID for the field element.
- **`idPrefix`** `string` — ID prefix to avoid collisions between multiple forms.

## Labels & Description

- **`label`** `ReactNode` — Label text displayed above or beside the input.
- **`labelPosition`** `'top' | 'side' | 'split'` (default: `top`) — Position of the label relative to the input. Side and split layouts reserve a label column only when a label is present.
- **`description`** `ReactNode` — Help text. It appears below a top label or the control when there is no visible label, and beside the control with a side or split label. It remains independent of the error message.
- **`isBare`** `boolean` — Render the control without field layout, description or message text. A supplied `label` remains as a visually hidden accessible label; label tooltips, suffixes and extra content are omitted. Form binding, invalid state and control styles still apply. Use this for an inline control that would otherwise show its chrome but has no room for it, or when a parent already renders that chrome. Provide `aria-describedby` when the error is explained elsewhere. Unset, a field renders its chrome when there is something to show: a non-empty `label`, a form binding, or a `description`, `errorMessage`, `message`, `fieldStyles`, `fieldProps` or `isHidden` prop, whatever it holds. On `TextInput`, `TextArea`, `PasswordInput` and `NumberInput`, which show the errors of a `validate`, that prop counts too. Otherwise it renders only the control. `TagInput` always has something to show: its refusal messages. Pass `isBare={false}` to render the chrome anyway. Style props size whichever element is outermost, so adding a label never changes where they apply; see _Field sizing and alignment_.
- **`forceField`** `boolean` — **Deprecated.** Use `isBare={false}`. Renders the chrome even with nothing to show; an explicit `isBare` wins.
- **`extra`** `ReactNode` — Additional content displayed next to the label.
- **`labelTooltip`** `ReactNode` — Content of an info badge shown next to the label. Only rendered when the field has a label. (Formerly `tooltip`. On most fields `tooltip` is gone; on `Select`, `Picker`, `FilterPicker`, `ColorPicker`, `Checkbox`, `Switch` and the text inputs (`TextInput`, `TextArea`, `PasswordInput`, `SearchInput`, `NumberInput`, `CommandTextArea`) it is the control's own tooltip, as on `Item` and `Button`.)
- **`labelSuffix`** `ReactNode` — Content displayed after the label text.
- **`labelProps`** `object` — Additional HTML props passed to the label element.
- **`labelStyles`** `Styles` — Tasty styles for the label element.
- **`labelRef`** `Ref<HTMLElement>` — The label element, visible or visually hidden with `isBare`; `null` without a `label`. A field's own `ref` is its control's, with or without the field chrome, so a bare field's is never `null`. Reach the field wrapper with `fieldProps={{ ref }}`.

## Field presentation

```jsx
// Nothing to show: only the control renders, with no field wrapper.
<TextInput aria-label="Search" />

// A form binding gives generated errors a place, even without a visible label.
<TextInput name="email" aria-label="Email" rules={[{ required: true, message: 'Enter an email' }]} />

// A bound control in a row that owns the label and error opts out explicitly.
<TextInput isBare name="amount" aria-label="Amount" aria-describedby="row-error" />

// Suppress only the error slot; keep the label and description.
<TextInput name="name" label="Name" description="Shown on invoices" errorMessage={null} />
```

The field wrapper stays in place when a description or message appears or disappears: a text prop counts whatever it holds, so pass `errorMessage={error}` rather than spreading the prop in only while there is an error. Adding or removing a `label` (an empty one counts as none) or a form binding, or changing `isBare`, changes the presentation structure and may remount the control; keep them stable while editing, or pass `isBare={false}` to keep the wrapper. Individual checkbox and radio options keep their group's inline presentation.

### Field sizing and alignment

An input's style props (`width`, `height`, `flex*`, `gridArea`, `margin`, `inset`, `position`, …) place and size its outer element: the field wrapper when it renders, the input itself otherwise. Adding a label never changes where they apply. When they size a wrapped field, the input stretches to fill it as it would in a grid cell of that size. Inputs with a fixed or capped size keep it: `Checkbox` and `Switch` their content width, single-line inputs and a vertical `Slider` their height. A side label's column is part of the width, and a split label keeps the input at its content width.

`width` is the space an input takes in the layout, label included. `controlWidth` is the control's own width: it sizes the element `width` sizes when the input renders bare, in every label position. On a bare input, with no label, description or form binding, the two reach the same element, so use `width` there; `controlWidth` wins when both are set. Beside a side label, `controlWidth` sizes the control alone, fixed, capped or following its value, however long the label is in a given language:

```jsx
// The field is 40x wide, label column included; the input fills it.
<TextInput label="Name" labelPosition="side" width="40x" />

// The select is 100px wide beside its label.
<Select label="Limit" labelPosition="side" controlWidth="100px">…</Select>

// The select fills the space beside its label, up to 30x.
<Select label="Compare with" labelPosition="side" controlWidth="max 30x">…</Select>

// The select follows its value, up to 30x.
<Select label="Compare with" labelPosition="side" controlWidth="initial max-content 30x">…</Select>

// The field is 40x wide; the input inside it stays 20x.
<TextInput label="Name" width="40x" controlWidth="20x" />
```

In a `Form`, a side label's column is the Form's `labelWidth` (25x by default) plus 1x, so the control starts `labelWidth` + 1x from the field's edge and is `controlWidth` wide. `controlWidth` wins over `styles.width`. `styles` always styles the input and `fieldStyles` always styles the wrapper: keep `styles` for restyling the input itself.

A style prop wins over `fieldStyles` for the same key. `fieldStyles` keeps working for everything else, but it never makes the input fill the field. Field-level inputs take only these style props and `controlWidth`; restyle the input through `styles` and its part props (`inputStyles`, `triggerStyles`, …).

A state map on a style prop resolves against the element it lands on, which is the wrapper on a labelled field. Use media, container or root states there, not the input's own states such as `focused`. A state map on `controlWidth` resolves against the control. `className`, `style`, `qa` and `ref` never move to the wrapper.

Fields without labels no longer reserve an empty side or split label column. If a row should intentionally align with neighbouring side labels, add `fieldStyles={{ padding: '$full-label-width left' }}`. For a nameless legacy `Form.Item`, put that padding on the item's `styles` instead; it owns the wrapper. Remove deprecated `forceField` when migrating these rows.

## Necessity Indicators

- **`isRequired`** `boolean` (default: `false`) — Whether user input is required before form submission. Marks the label, sets `aria-required` on the input, and adds a `required` validation rule.
- **`isOptional`** `boolean` (default: `false`) — Marks the label with a quiet `(optional)` note. Presentational only: it changes no validation behaviour, and it is ignored when the field is required.
- **`necessityIndicator`** `'icon' | 'label' | null` (default: `icon`) — Shape of the marker. `'icon'` renders the asterisk, `'label'` the `(required)` text, `null` suppresses it. `(optional)` has no icon form and always renders as text.
- **`requiredMark`** `boolean` (default: `true`) — Set it to `false` — usually on the `Form` — to drop the required marker across fields that ask for one.

**The marker is opt-in.** A `{ required: true }` rule states how the field _behaves_: it is what validation runs, and `aria-required` is its programmatic mirror, so both stay in place. It does not decorate the label. Pass `isRequired` when you want the marker too — it adds the rule for you, so the two are interchangeable as far as validation goes:

```jsx
{/* Validated and announced as required, but the label is left alone */}
<TextInput name="email" label="Email" rules={[{ required: true }]} />

{/* The same validation, plus the marker */}
<TextInput name="email" label="Email" isRequired />

{/* Asking for the marker on a rule-required field, without repeating the rule */}
<TextInput
  name="email"
  label="Email"
  necessityIndicator="icon"
  rules={[{ required: true }]}
/>

{/* Optional is a note, never a rule */}
<TextInput name="nickname" label="Nickname" isOptional />
```

## State

- **`isDisabled`** `boolean` (default: `false`) — Whether the field is disabled and non-interactive. A field also takes it from an enclosing `<Provider isDisabled>` or `<Form isDisabled>`, including when its own `isDisabled` is `undefined`. Buttons don't, apart from `Form.Submit` and `Form.Reset`: see [Button](./components/actions/Button.md).
- **`isReadOnly`** `boolean` (default: `false`) — Whether the field can be focused but not changed.
- **`isLoading`** `boolean` (default: `false`) — Whether the field shows its loading spinner. `Select`, `Picker`, `FilterPicker`, `ColorPicker` and a button-type `Radio` also disable while loading; other fields stay interactive, and fields without a spinner, such as `Checkbox`, `RadioGroup`, `ListBox` or `Slider`, ignore it.
- **`isHidden`** `boolean` (default: `false`) — Whether the field is hidden.
- **`isInvalid`** `boolean` (default: `false`) — Whether the field displays its invalid visual styling. Takes precedence over `isValid`.
- **`isValid`** `boolean` (default: `false`) — Whether the field displays its valid visual styling.
- **`validationState`** `'valid' | 'invalid'` — _(deprecated)_ Use `isInvalid` / `isValid` instead.
- **`autoFocus`** `boolean` (default: `false`) — Whether the field should receive focus on render.

## Validation

- **`rules`** `ValidationRule[]` — Array of validation rules for the field.
- **`validateTrigger`** `'onBlur' | 'onChange' | 'onSubmit'` — When to trigger validation.
- **`validationDelay`** `number` — Debounce delay in milliseconds before running validation.
- **`deps`** `readonly unknown[]` — Modern validator inputs captured from outside the form. Compared with `Object.is`; changes invalidate prior validation.
- **`dependsOn`** `readonly FormPath[]` — Modern form paths that trigger revalidation, including conditional reads. Validator reads only cancel in-flight work.
- **`rulesKey`** `string` — Manual modern function revision. Skips validator/transform source comparison; declarative constraints are always compared. Update it when a function or its captures change.
- **`errorPolicy`** `'first' | 'all'` — Modern rule error collection policy, inherited from the controller by default.
- **`showValid`** `boolean` — Whether to show the valid state icon after successful validation.
- **`errorMessage`** `ReactNode` — Error text displayed in danger state, regardless of validation state. `undefined` allows the form-generated error or the deprecated `message` fallback. An explicit `null`, `false` or empty string suppresses the error text and its fallback, while the control retains its invalid state. The description remains visible.
- **`message`** `ReactNode` — _(deprecated)_ Fallback text used only when `errorMessage` is `undefined`. Use `errorMessage` for errors and `description` for help text. `message={null}` does not suppress a generated `errorMessage`.

## Styling

- **`controlWidth`** `Styles['width']` — The control's own width, in every label position: the element `width` sizes when the input renders bare. Beside a side label it sizes the control alone. It wins over `width` on a bare input and over `styles.width`; see _Field sizing and alignment_.
- **`fieldStyles`** `Styles` — Tasty styles for the field wrapper. A style prop for the same key wins over it.
- **`messageStyles`** `Styles` — Tasty styles for the message/error text.

## Validation Rules

The `rules` prop accepts an array of rule objects. Built-in validators include:

- **`required`** `boolean` — Field must have a value.
- **`type`** `string` — Validates data type (`email`, `url`, `number`, etc.).
- **`pattern`** `RegExp` — Value must match the regular expression.
- **`min`** / **`max`** `number` — Minimum/maximum length or value constraints.
- **`enum`** `any[]` — Value must be one of the allowed values.
- **`whitespace`** `boolean` — Value must contain non-whitespace characters.
- **`message`** `string` — Custom error message for the rule.
- **`validator`** `(rule, value, context) => result` — Custom rule function. In modern forms, return an error or throw/reject to fail; `undefined`, `null`, and an empty string succeed. The context provides `signal`, `name`, `getValue`, and `getValues`. Prefer descriptor `validate(value, context)` for an ordinary custom check with an inferred value type. Legacy validators retain their existing contract.

```tsx
<TextInput
  field={form.field('email', {
    rules: [{ type: 'email', message: 'Enter a valid email' }],
  })}
  label="Email Address"
  isRequired
/>
```

## Usage Example

```tsx
import { Form, TextInput, Select } from '@cube-dev/ui-kit';

function ExampleForm() {
  const form = Form.useController<{
    name: string;
    role: 'admin' | 'member' | null;
  }>({ defaultValues: { name: '', role: null } });

  return (
    <Form form={form}>
      <TextInput
        name="name"
        rules={[{ min: 2 }]}
        label="Full Name"
        description="As it appears on your ID"
        isRequired
      />

      <Select
        name="role"
        label="Role"
        labelTooltip="Your primary role in the organization"
        necessityIndicator="label"
        isRequired
      >
        <Select.Item key="admin">Admin</Select.Item>
        <Select.Item key="member">Member</Select.Item>
      </Select>

      <Form.Submit>Save</Form.Submit>
    </Form>
  );
}
```

## Related

- [Base Properties](./BaseProperties.md) — Common styling and layout properties
- [Form](./components/form/Form.md) — Form container with validation and state management
- [Field](./components/form/Field.md) — Legacy field wrapper (for custom components only)
