# Field

把表单控件连接到它的标签、描述和校验错误。

字段把表单控件连接到它的标签、描述和它显示的错误，并为你接好 `id`、`for` 和 `aria-describedby`。

```vue title="input.vue"
<script setup lang="ts">
import { Field, FieldDescription, FieldLabel } from "@ui-sdk/vue/field"
import { Input } from "@ui-sdk/vue/input"
</script>

<template>
  <div data-slot="stack">
    <Field>
      <FieldLabel>Username</FieldLabel>
      <Input name="username" placeholder="hollis" autocomplete="username" />
      <FieldDescription
        >Choose a unique username for your account.</FieldDescription
      >
    </Field>
  </div>
</template>
```

点击 Username 让输入框获得焦点，然后输入一个名字。

## 安装
```bash
npm install @ui-sdk/vue @ui-sdk/core
```

## 组合
用下面的组合构建一个 `Field`：

```text
Field
├── FieldLabel
├── Input
├── FieldDescription
└── FieldError
```

## 用法
```vue
<script setup lang="ts">
import {
  Field,
  FieldDescription,
  FieldError,
  FieldLabel,
} from "@ui-sdk/vue/field"
import { Input } from "@ui-sdk/vue/input"
</script>

<template>
  <Field name="username">
    <FieldLabel>Username</FieldLabel>
    <Input autocomplete="username" required />
    <FieldDescription>This is your public name.</FieldDescription>
    <FieldError />
  </Field>
</template>
```

控件可以是我们提供的组件，比如 [Input](/docs/vue/components/input)、[Textarea](/docs/vue/components/textarea)、[Select](/docs/vue/components/select) 或 [Checkbox](/docs/vue/components/checkbox)，它会自己连接到字段。

标签为控件提供名称，描述和任何显示出来的错误则说明它。

把相关的字段归入一个[字段集](https://ui-sdk.cn/docs/vue/components/field#field-sets)：

```vue
<FieldSet>
  <FieldLegend />
  <FieldDescription />
  <FieldGroup>
    <Field />
    <Field />
  </FieldGroup>
</FieldSet>
```

## 控件
一行文本用 [Input](/docs/vue/components/input)，更多内容用 [Textarea](/docs/vue/components/textarea)：

```vue
<Field>
  <FieldLabel>Feedback</FieldLabel>
  <Textarea name="feedback" />
</Field>
```

对于我们不提供的控件，比如原生 `<select>`，请用 `FieldControl`。它渲染一个 `<input>`，或通过 `render` 插槽渲染另一个元素，并用同样的方式把它连接到字段。[智能体](/docs/agents)只能看到我们的组件，所以它无法填写 `FieldControl`：有我们的组件时就用我们的。

```vue
<Field>
  <FieldLabel>Department</FieldLabel>
  <FieldControl name="department">
    <template #render="{ props }">
      <select v-bind="props">
        <option value="design">Design</option>
        <option value="engineering">Engineering</option>
      </select>
    </template>
  </FieldControl>
</Field>
```

字段里的 [Checkbox](/docs/vue/components/checkbox)、[Switch](/docs/vue/components/switch) 或 [Radio Group](/docs/vue/components/radio) 会使用字段的标签和描述。按压标签会切换复选框或开关。单选组会把字段的标签当作自己的名称，每个单选项则保留自己的标签：

```vue
<Field>
  <Switch name="mfa" />
  <FieldLabel>Two-factor authentication</FieldLabel>
  <FieldDescription>Ask for a code when you sign in.</FieldDescription>
</Field>

<Field>
  <FieldLabel>Plan</FieldLabel>
  <RadioGroup name="plan" default-value="monthly">
    <label>
      <Radio value="monthly" />
      Monthly
    </label>
    <label>
      <Radio value="yearly" />
      Yearly
    </label>
  </RadioGroup>
</Field>
```

## 校验
使用原生约束，比如 `required`、`type="email"` 和 `pattern`。错误会在尝试提交后出现，并随值的变化而更新。第一个无效的控件会获得焦点。

把错误留空可显示浏览器的消息；要用自己的消息，就用 `match="valueMissing"` 和 `match="typeMismatch"`。加上错误部件后，页面里的这条消息会取代浏览器原生的校验气泡。

```vue title="validation.vue"
<script setup lang="ts">
import {
  Field,
  FieldDescription,
  FieldError,
  FieldLabel,
} from "@ui-sdk/vue/field"
import { Input } from "@ui-sdk/vue/input"
import { useLog } from "./log"

const log = useLog()

function submit(event: Event) {
  log(
    `Subscribed ${new FormData(event.currentTarget as HTMLFormElement).get("email")}`
  )
}
</script>

<template>
  <form data-slot="stack" @submit.prevent="submit">
    <Field name="email">
      <FieldLabel>Email</FieldLabel>
      <Input type="email" required placeholder="hollis@example.com" />
      <FieldDescription v-slot="{ state }">
        {{
          state.valid ? "Looks good." : "We'll send you a confirmation link."
        }}
      </FieldDescription>
      <FieldError match="valueMissing">Enter your email address.</FieldError>
      <FieldError match="typeMismatch"
        >Enter an email address like hollis@example.com.</FieldError
      >
    </Field>
    <Field name="website">
      <FieldLabel>Website</FieldLabel>
      <Input type="url" required placeholder="https://example.com" />
      <FieldError />
    </Field>
    <button type="submit" data-variant="solid">Subscribe</button>
  </form>
</template>
```

在邮箱为空或无效时点击 Subscribe，然后改正它来清除错误。

## 来自你的代码的错误
当服务器或表单库给出错误时，传入 `invalid`。`true` 会立即显示它。清除值即可回到浏览器的校验。

给这个错误单独的文本，并把 `match` 设为 `true`。`valueMissing` 这类具名匹配仍然指原生校验。`:invalid="false"` 会隐藏字段的无效状态，但不会让无效的原生控件通过校验。

```vue
<Field name="email" :invalid="serverError ? true : undefined">
  <FieldLabel>Email</FieldLabel>
  <Input type="email" required @value-change="serverError = null" />
  <FieldError match="valueMissing">Enter your email address.</FieldError>
  <FieldError v-if="serverError" match>{{ serverError }}</FieldError>
</Field>
```

## 必填与禁用
必填控件会给每个部件标记 `data-required`，部件的状态里也有 `required`，所以只靠 CSS 就能让标签显示标记。

禁用的字段会禁用它的控件，并给每个部件标记 `data-disabled`，就像[禁用的字段集](https://ui-sdk.cn/docs/vue/components/field#disabled-field-sets)对它里面的每个字段所做的那样。

## 字符计数
把文本放在状态里，并在描述里显示它的长度。在控件上设置 `maxlength`，让这个限制生效。

```vue
<Field>
  <FieldLabel>Bio</FieldLabel>
  <Textarea v-model:value="bio" :maxlength="280" />
  <FieldDescription>{{ bio.length }} / 280</FieldDescription>
</Field>
```

## 表单
控件用自己的 `name` 提交它的值；没有 `name` 时，就用字段的 `name`。重置会恢复控件的默认值，并隐藏校验错误。禁用的控件不会包含在提交的值里。共享的表单行为见[表单](/docs/vue/forms)。

## 字段集
字段集把相关的字段归到一个图例（legend）下，并一起禁用它们。

```vue title="field-set.vue"
<script setup lang="ts">
import {
  Field,
  FieldDescription,
  FieldGroup,
  FieldLabel,
  FieldLegend,
  FieldSet,
} from "@ui-sdk/vue/field"
import { Input } from "@ui-sdk/vue/input"
</script>

<template>
  <FieldSet>
    <FieldLegend>Address</FieldLegend>
    <FieldDescription
      >We need your address to deliver your order.</FieldDescription
    >
    <FieldGroup>
      <Field name="street">
        <FieldLabel>Street address</FieldLabel>
        <Input autocomplete="street-address" />
      </Field>
      <div data-slot="grid">
        <Field name="city">
          <FieldLabel>City</FieldLabel>
          <Input autocomplete="address-level2" />
        </Field>
        <Field name="postal-code">
          <FieldLabel>Postal code</FieldLabel>
          <Input autocomplete="postal-code" />
        </Field>
      </div>
    </FieldGroup>
  </FieldSet>
</template>
```

在地址字段之间移动。它们的图例和描述为这个分组命名。

`FieldSet` 是原生 `<fieldset>`，`FieldLegend` 是原生 `<legend>`，所以字段集在脚本运行之前就有了名称，也能被禁用。让图例保持为第一个子元素。通过 `render` 插槽渲染成其他元素的图例，比如 `<div>`，仍然通过 `aria-labelledby` 为字段集命名。

直接放在字段集里、不在任何 `Field` 之内的 `FieldDescription` 描述的是字段集，所以焦点进入时屏幕阅读器会读出它。`FieldGroup` 是一个堆叠字段的 `<div>`，没有角色也没有状态：为分组命名和禁用的都是字段集。

## 禁用字段集
禁用字段集会禁用它的控件和嵌套的字段集。表单提交时不会包含它们的值。

```vue
<FieldSet :disabled="sameAsShipping">
  <FieldLegend>Billing address</FieldLegend>
  <Field name="billing-street">
    <FieldLabel>Street address</FieldLabel>
    <Input autocomplete="billing street-address" />
  </Field>
</FieldSet>
```

## 字段集里的分组
图例会为字段集里的[复选框组](https://ui-sdk.cn/docs/vue/components/checkbox#group)或[单选组](/docs/vue/components/radio)命名，所以分组不需要自己的标签。

```vue
<FieldSet>
  <FieldLegend>Notifications</FieldLegend>
  <CheckboxGroup name="notify" :default-value="['mentions']">
    <label>
      <Checkbox value="mentions" />
      Mentions
    </label>
    <label>
      <Checkbox value="follows" />
      New followers
    </label>
  </CheckboxGroup>
</FieldSet>
```

## 自定义渲染
每个部件都接受 `render` 插槽，用来在原地渲染别的元素或组件，比如 `FieldControl` 的 `<select>`。它会收到要绑定的 props 和字段的状态：

```vue
<FieldDescription>
  <template #render="{ props, state }">
    <p v-bind="props">{{ state.invalid ? "Use letters and numbers only." : "Letters and numbers." }}</p>
  </template>
</FieldDescription>
```

默认插槽也会以 `v-slot="{ state }"` 收到状态。`FieldError` 的状态里还有当前问题的 `message`。

状态是惰性读取的。只有当部件的渲染函数或槽位读过某个值时，这个值的变化才会让部件重新渲染。每个部件的状态列在[状态](https://ui-sdk.cn/docs/vue/components/field#state)下。

## 自定义控件
`useFieldControl` 让你自己的控件像我们的控件一样加入它周围的字段。在字段之外，它返回 `null`。在字段之内，它返回：

- `name()`：字段的 `name`，供没有自己设置 `name` 的控件使用。
- `disabled()`：字段是否被禁用。
- `props(props)`：把字段的 props 合并进控件的 props：`id`、`aria-labelledby`、`aria-describedby`、`aria-invalid`、`disabled` 和字段的数据属性，以及一个告诉字段哪个元素是它控件的 ref。控件保留自己的 `data-slot`。

在渲染时调用 `props`，比如在模板里，这样字段变化时控件会更新，比如它的标签或错误出现时。

```vue
<script setup lang="ts">
import { useAttrs } from "vue"
import { useFieldControl } from "@ui-sdk/vue/field"

defineOptions({ inheritAttrs: false })
const attrs = useAttrs()
const field = useFieldControl()
const input = () => ({
  type: "tel",
  autocomplete: "tel",
  name: field?.name(),
  ...attrs,
  "data-slot": "phone-input",
})
</script>

<template>
  <input v-bind="field ? field.props(input()) : input()" />
</template>
```

```vue
<Field>
  <FieldLabel>Phone</FieldLabel>
  <PhoneInput required />
  <FieldError />
</Field>
```

字段会从它里面的原生 input、select 和 textarea 读取有效性，所以上面的 input 上 `required` 和 `pattern` 能生效。不是原生 input 的控件，比如一排按钮，会通过自己的一个原生 input 参与：我们的控件会在它旁边渲染一个视觉上隐藏的 input。

想用我们的控件所用的原语（primitive）从零构建控件，请参阅[原语](/docs/core/kernel/define-a-primitive)。

## 样式
校验用 `data-invalid` 和 `data-valid`，其余用 `data-focused`、`data-required` 和 `data-disabled`。字段的每个部件都会拿到相同的属性，所以标签可以随控件一起变红。

每个部件都有一个 `data-slot`，比如 `field-label`，它的状态属性列在[数据属性](https://ui-sdk.cn/docs/vue/components/field#data-attributes)下。

## 数据属性
### Field
`[data-slot="field"]`

- `data-disabled`: Present when the field is disabled.
- `data-invalid`: Present while the field shows as invalid: with `invalid`, or once a submit finds the control invalid.

### FieldLabel
`[data-slot="field-label"]`

- `data-disabled`: Present when the field is disabled.
- `data-invalid`: Present while the field shows as invalid: with `invalid`, or once a submit finds the control invalid.

### FieldControl
`[data-slot="field-control"]`

- `data-disabled`: Present when the field is disabled.
- `data-invalid`: Present while the field shows as invalid: with `invalid`, or once a submit finds the control invalid.

### FieldDescription
`[data-slot="field-description"]`

- `data-disabled`: Present when the field is disabled.
- `data-invalid`: Present while the field shows as invalid: with `invalid`, or once a submit finds the control invalid.

### FieldError
`[data-slot="field-error"]`

- `data-disabled`: Present when the field is disabled.
- `data-invalid`: Present while the field shows as invalid: with `invalid`, or once a submit finds the control invalid.

### FieldSet
`FieldGroup` 有 `data-slot="field-group"`，没有状态属性。

`[data-slot="field-set"]`

- `data-disabled`: Present when the field set is disabled, by its own prop or a `<fieldset>` around it.

### FieldLegend
`[data-slot="field-legend"]`

- `data-disabled`: Present when the field set is disabled, by its own prop or a `<fieldset>` around it.

### FieldSet 里的 FieldDescription
`[data-slot="field-description"]`

- `data-disabled`: Present when the field set is disabled, by its own prop or a `<fieldset>` around it.

## API 参考
属性与下面相同。

字段没有变更事件。从部件的数据属性或渲染函数里读取它的状态。设置 `debug` 可以记录每次状态变化及其原因。

### Field
- `name?` (`string`): The name the control submits under, when the control doesn't set its own.
- `disabled?` (`boolean`): Disables the control, and marks every part.
- `invalid?` (`boolean`): Whether the field shows as invalid, when your code decides, like a form library or an error from the server. `true` shows its errors now, `false` shows none whatever the browser thinks. Leave it out to show the browser's own validation once a submit finds the field invalid.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### FieldError
- `match?` (`boolean | ValidityKey`): When this error shows. `true` shows it always and `false` never. A validity flag, like `"valueMissing"`, shows it only for that problem of the browser's own validation. Without it, any problem shows it.

### FieldSet
- `disabled?` (`boolean`): Disables every control inside it, except those in its legend, and leaves them out of the form.
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.

### 状态
- `disabled` (`boolean`): Whether the field is disabled, by itself or by a `<fieldset>`.
- `required` (`boolean`): Whether the control is required, read from its `required` or `aria-required`.
- `focused` (`boolean`): Whether focus is inside the control.
- `invalid` (`boolean`): Whether the field shows as invalid: `invalid` when you pass it, else the browser's validation once shown.
- `valid` (`boolean`): Whether the browser's validation passes, once shown. Always false while you pass `invalid`.

- `disabled` (`boolean`): Whether the field is disabled, by itself or by a `<fieldset>`.
- `required` (`boolean`): Whether the control is required, read from its `required` or `aria-required`.
- `focused` (`boolean`): Whether focus is inside the control.
- `invalid` (`boolean`): Whether the field shows as invalid: `invalid` when you pass it, else the browser's validation once shown.
- `valid` (`boolean`): Whether the browser's validation passes, once shown. Always false while you pass `invalid`.
- `message` (`string`): The browser's message for the current problem. Children you pass show instead.

`FieldDescription` 会收到字段的状态；当它描述字段集时，只收到 `disabled`。

- `disabled` (`boolean`): Whether the field set is disabled, by itself or by a field set around it. Whether the field is disabled, by itself or by a `<fieldset>`.
- `required` (`boolean | undefined`): Whether the control is required, read from its `required` or `aria-required`.
- `focused` (`boolean | undefined`): Whether focus is inside the control.
- `invalid` (`boolean | undefined`): Whether the field shows as invalid: `invalid` when you pass it, else the browser's validation once shown.
- `valid` (`boolean | undefined`): Whether the browser's validation passes, once shown. Always false while you pass `invalid`.

字段集的每个部件都会收到相同的状态。

- `disabled` (`boolean`): Whether the field set is disabled, by itself or by a field set around it.

## 无障碍
标签通过 `aria-labelledby` 为控件提供名称，控件能接受原生 `<label for>` 时还会同时用它。描述和任何显示出来的错误通过 `aria-describedby` 描述它，无效的控件带有 `aria-invalid`。下面的测试覆盖这些关联和键盘行为。

**Labelling**

- The label names the control.
- The description describes the control.
- Clicking the label of a text field focuses it.

**A label wrapping a field**

- Names the control inside it.
- Checks its control when clicked anywhere.
- Keeps the field's description on its control.
- Names a control that renders after it.
- Keeps the part's data-slot.
- Warns in development only when a label outside a field labels nothing.
- A description and an error outside a field keep their data-slot. Web components only.
- A hidden error outside a field stays hidden whatever display its class gives. Web components only.
- An error outside a field follows its match. Web components only.
- An error outside a field shows a child that arrives after it. Web components only.

**Errors**

- Stay hidden until the form tries to submit.
- Show the browser's message when they have no text of their own.
- Count another library's form-associated element inside the field.
- Describe the control while they show.
- Update as the value changes once shown.
- Update as state set from script changes the value once shown. Web components only.
- A field marked invalid shows its error right away.
- A field marked valid never shows the browser's errors.
- A form reset hides them again.
- Errors in the page replace the browser's message, and the first invalid control takes focus.

Runs in React、Vue 和 web components.

在字段集里：

- The legend names the group.
- A disabled field set disables the controls inside and leaves them out of the form.
- Enabling it again restores the controls.
- A field set disabled from the start disables its required fields.
- Fields in a disabled field set mark their parts disabled.

**Enhancements**

- The description describes the group.

Runs in React、Vue 和 web components.

在表单里：

- The form submits every checked control's name and value.
- Unchecked controls submit nothing.
- A checkbox outside the form joins it with the form attribute.
- Required controls block submission.
- A form reset returns every control to its default.
- A reset returns to the default value, not to nothing.
- A disabled fieldset disables the controls inside it.
- A read-only control still submits.
- A user's change fires native input and change events on the form.

Runs in React、Vue 和 web components.
