# Field

> A form row that ties one control to its label, description and error.

```tsx title="hero.tsx"
import { Field, FieldDescription, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { Input } from '@langgenius/dify-ui/input'

export function FieldHeroDemo() {
  return (
    <Field name="endpoint" validationMode="onBlur" className="w-full max-w-96">
      <FieldLabel>API endpoint</FieldLabel>
      <Input
        type="url"
        required
        placeholder="https://api.example.com/v1"
        autoComplete="off"
        autoCapitalize="none"
        autoCorrect="off"
        spellCheck={false}
      />
      <FieldDescription>Dify sends extension requests to this base URL.</FieldDescription>
      <FieldError match="valueMissing">Enter an API endpoint.</FieldError>
      <FieldError match="typeMismatch">
        Enter a valid URL, such as https://api.example.com/v1.
      </FieldError>
    </Field>
  )
}
```

## Usage guidelines

- Use `Field` when one control needs a shared `name`, a label, a description, validation or an error. Group several related controls with [`Fieldset`](/components/fieldset.md), and submit fields together with a [`Form`](/components/form.md).
- A `Field` describes one control. A composite that renders its own controls, such as a picker with controls in its popup, does not go inside one.
- Name the control with a visible `FieldLabel`: text inputs, `Textarea`, input-based `Combobox` and `Autocomplete`, a single `Checkbox`, `Switch` and `NumberField`. `Select`, `Slider` and the date and time pickers use their own label parts. A `placeholder` or a tooltip is never the only name.
- `FieldDescription` and `FieldError` describe the control through `aria-describedby`. Do not add a second label or a competing description to the control.
- Set `name` on the `Field`. It keys the value in the submitted form values and the server errors that `Form` maps back to the field.
- Pick one source of validity per rule: native constraint attributes such as `required`, `type` and `minLength`; a `validate` function; or `Form` `errors` from the server. When application code owns validity, set `invalid` on the `Field` and render `FieldError match` only while it is invalid.

See the [forms guide](/guides/forms.md) for the full model.

## Anatomy

```tsx
import {
  Field,
  FieldDescription,
  FieldError,
  FieldItem,
  FieldLabel,
  FieldValidity,
} from '@langgenius/dify-ui/field'
import { Input } from '@langgenius/dify-ui/input'
```

```tsx
<Field>
  <FieldLabel />
  <Input />
  <FieldDescription />
  <FieldError />
  <FieldValidity />
</Field>
```

The control is any dify-ui form control, such as `Input`, `Textarea`, `Checkbox` or `Switch`; it reads its ID, name and validity from the surrounding `Field`. `FieldItem` wraps each checkbox or radio option inside a group, see [Fieldset](/components/fieldset.md). `FieldValidity` passes the current validity state to a render function for custom feedback.

## Examples

### Reading validity state

Native attributes (`required`, `minLength`, `pattern`) drive each matched `FieldError` so every message stays in your own words. `FieldValidity` passes the live validity flags and current value to a render function for custom feedback—such as showing the published URL once the slug is valid. Try `a`, `My Bot` or `support-bot`.

```tsx title="validity.tsx"
import {
  Field,
  FieldDescription,
  FieldError,
  FieldLabel,
  FieldValidity,
} from '@langgenius/dify-ui/field'
import { Input } from '@langgenius/dify-ui/input'

export function FieldValidityDemo() {
  return (
    <Field name="slug" validationMode="onChange" className="w-full max-w-96">
      <FieldLabel>Web app slug</FieldLabel>
      <Input
        required
        minLength={3}
        maxLength={32}
        pattern="[a-z0-9]+(?:-[a-z0-9]+)*"
        placeholder="support-bot"
        autoComplete="off"
        autoCapitalize="none"
        autoCorrect="off"
        spellCheck={false}
      />
      <FieldDescription>3 to 32 lowercase letters, digits or hyphens.</FieldDescription>
      <FieldError match="valueMissing">Enter a web app slug.</FieldError>
      <FieldError match="tooShort">Use at least 3 characters.</FieldError>
      <FieldError match="patternMismatch">
        Use lowercase letters, digits and single hyphens.
      </FieldError>
      <FieldValidity>
        {({ validity, value }) => {
          const slug = typeof value === 'string' ? value : ''
          if (!validity.valid || !slug) return null
          return (
            <p
              role="status"
              className="flex items-center gap-1.5 py-0.5 body-xs-regular text-text-success"
            >
              <span aria-hidden="true" className="i-ri-checkbox-circle-line size-3.5 shrink-0" />
              <span className="min-w-0 truncate">
                Published at <span className="font-mono">/chat/{slug}</span>
              </span>
            </p>
          )
        }}
      </FieldValidity>
    </Field>
  )
}
```

### Custom validation

`validate` runs after the native constraints pass. Return a message for an invalid value and `null` for a valid one; a `FieldError` without children shows the returned message. This field uses `validationMode="onChange"`, so it checks every keystroke: try `_query`, `sys` or `User Query`. Add `validationDebounceTime` when the check is a request.

```tsx title="custom-validation.tsx"
import { Field, FieldDescription, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { Input } from '@langgenius/dify-ui/input'

const reservedNames = ['sys', 'env', 'conversation']

export function FieldCustomValidationDemo() {
  return (
    <Field
      name="variable"
      validationMode="onChange"
      className="w-full max-w-96"
      validate={(value) => {
        const name = typeof value === 'string' ? value : ''
        if (!name) return 'Enter a variable name.'
        if (!/^[a-z][a-z0-9_]*$/.test(name))
          return 'Use lowercase letters, digits and underscores, starting with a letter.'
        if (reservedNames.includes(name)) return `${name} is reserved by Dify.`
        return null
      }}
    >
      <FieldLabel>Variable name</FieldLabel>
      <Input
        defaultValue="user_query"
        placeholder="document_text"
        autoComplete="off"
        autoCapitalize="none"
        autoCorrect="off"
        spellCheck={false}
      />
      <FieldDescription>Referenced in prompts as {'{{variable_name}}'}.</FieldDescription>
      <FieldError />
    </Field>
  )
}
```

### Validity owned by the application

When a form library or other application code decides validity, pass `invalid` to the `Field` and render `FieldError` with `match` while the field is invalid. `match` without a validity key shows the message regardless of state, so the condition belongs to the application. Replace the legacy key with a new `app-` key to clear the error.

```tsx title="external-invalid.tsx"
import { Field, FieldDescription, FieldError, FieldLabel } from '@langgenius/dify-ui/field'
import { Input } from '@langgenius/dify-ui/input'
import * as React from 'react'

function getApiKeyError(value: string) {
  const trimmed = value.trim()
  if (!trimmed) return 'Enter an app API key.'
  if (trimmed.startsWith('app-legacy-'))
    return 'Legacy keys no longer work. Create a new key and paste it here.'
  if (!/^app-[a-z0-9-]+$/i.test(trimmed))
    return 'Enter a key starting with app-, using letters, digits or hyphens.'
  return null
}

export function FieldExternalInvalidDemo() {
  const [apiKey, setApiKey] = React.useState('app-legacy-7f3a9c')
  const errorMessage = getApiKeyError(apiKey)

  return (
    <Field name="apiKey" invalid={errorMessage !== null} className="w-full max-w-96">
      <FieldLabel>App API key</FieldLabel>
      <Input
        placeholder="app-…"
        value={apiKey}
        onValueChange={setApiKey}
        autoComplete="off"
        autoCapitalize="none"
        autoCorrect="off"
        spellCheck={false}
      />
      <FieldDescription>Find the key under API Access in the app.</FieldDescription>
      {errorMessage && <FieldError match>{errorMessage}</FieldError>}
    </Field>
  )
}
```

### Checkbox or switch label

For a single checkbox or switch, wrap the control in `FieldLabel` so the whole label toggles it. The description still describes the control.

```tsx title="switch.tsx"
import { Field, FieldDescription, FieldLabel } from '@langgenius/dify-ui/field'
import { Switch } from '@langgenius/dify-ui/switch'

export function FieldSwitchDemo() {
  return (
    <Field name="citations" className="w-full max-w-96 gap-0.5">
      <FieldLabel className="flex w-full items-center justify-between gap-4">
        Show citations
        <Switch defaultChecked />
      </FieldLabel>
      <FieldDescription>Lists the knowledge sources under each answer.</FieldDescription>
    </Field>
  )
}
```

## API reference

### Field

Groups a form control with its label, description, error message, and validation state. Renders a `<div>` element.

Inherits `render`, `style`, `disabled`, `name`, `validate`, `validationMode`, `validationDebounceTime`, `invalid`, `dirty`, `touched`, `actionsRef`, `className` from [Base UI Field.Root](https://base-ui.com/react/components/field#root).

**Data attributes**

| Attribute       | Description                                 |
| --------------- | ------------------------------------------- |
| `data-disabled` | Present when the field is disabled.         |
| `data-touched`  | Present when the field has been touched.    |
| `data-dirty`    | Present when the field's value has changed. |
| `data-valid`    | Present when the field is valid.            |
| `data-invalid`  | Present when the field is invalid.          |
| `data-filled`   | Present when the field is filled.           |
| `data-focused`  | Present when the field control is focused.  |

### FieldDescription

A paragraph with additional information about the field. Renders a `<p>` element.

Inherits `className`, `render`, `style` from [Base UI Field.Description](https://base-ui.com/react/components/field#description).

**Data attributes**

| Attribute       | Description                                    |
| --------------- | ---------------------------------------------- |
| `data-disabled` | Present when the field is disabled.            |
| `data-valid`    | Present when the field is in a valid state.    |
| `data-invalid`  | Present when the field is in an invalid state. |
| `data-touched`  | Present when the field has been touched.       |
| `data-dirty`    | Present when the field's value has changed.    |
| `data-filled`   | Present when the field is filled.              |
| `data-focused`  | Present when the field control is focused.     |

### FieldError

An error message displayed if the field control fails validation. Renders a `<div>` element.

Inherits `match`, `className`, `render`, `style` from [Base UI Field.Error](https://base-ui.com/react/components/field#error).

**Data attributes**

| Attribute             | Description                                         |
| --------------------- | --------------------------------------------------- |
| `data-disabled`       | Present when the field is disabled.                 |
| `data-valid`          | Present when the field is in a valid state.         |
| `data-invalid`        | Present when the field is in an invalid state.      |
| `data-touched`        | Present when the field has been touched.            |
| `data-dirty`          | Present when the field's value has changed.         |
| `data-filled`         | Present when the field is filled.                   |
| `data-focused`        | Present when the field control is focused.          |
| `data-starting-style` | Present when the error message begins animating in. |
| `data-ending-style`   | Present when the error message is animating out.    |

### FieldItem

Groups individual items in a checkbox group or radio group with a label and description. Renders a `<div>` element.

Inherits `disabled`, `className`, `render`, `style` from [Base UI Field.Item](https://base-ui.com/react/components/field#item).

**Data attributes**

| Attribute       | Description                                    |
| --------------- | ---------------------------------------------- |
| `data-disabled` | Present when the field is disabled.            |
| `data-valid`    | Present when the field is in a valid state.    |
| `data-invalid`  | Present when the field is in an invalid state. |
| `data-touched`  | Present when the field has been touched.       |
| `data-dirty`    | Present when the field's value has changed.    |
| `data-filled`   | Present when the field is filled.              |
| `data-focused`  | Present when the field control is focused.     |

### FieldLabel

An accessible label that is automatically associated with the field control. Renders a `<label>` element.

Inherits `nativeLabel`, `className`, `render`, `style` from [Base UI Field.Label](https://base-ui.com/react/components/field#label).

**Data attributes**

| Attribute       | Description                                    |
| --------------- | ---------------------------------------------- |
| `data-disabled` | Present when the field is disabled.            |
| `data-valid`    | Present when the field is in a valid state.    |
| `data-invalid`  | Present when the field is in an invalid state. |
| `data-touched`  | Present when the field has been touched.       |
| `data-dirty`    | Present when the field's value has changed.    |
| `data-filled`   | Present when the field is filled.              |
| `data-focused`  | Present when the field control is focused.     |

### FieldValidity

Used to display a custom message based on the field's validity. Requires `children` to be a function that accepts field validity state as an argument.

Inherits `children` from [Base UI Field.Validity](https://base-ui.com/react/components/field#validity).
