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

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

<script lang="ts">
  import { Field, FieldDescription, FieldLabel } from "@ui-sdk/svelte/field"
  import { Input } from "@ui-sdk/svelte/input"
</script>

<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>
点击 Username 让输入框获得焦点,然后输入一个名字。

安装

npm install @ui-sdk/svelte @ui-sdk/core

组合

用下面的组合构建一个 Field:

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

用法

<script lang="ts">
  import {
    Field,
    FieldDescription,
    FieldError,
    FieldLabel,
  } from "@ui-sdk/svelte/field"
  import { Input } from "@ui-sdk/svelte/input"
</script>

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

控件可以是我们提供的组件,比如 Input、Textarea、Select 或 Checkbox,它会自己连接到字段。

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

把相关的字段归入一个字段集:

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

控件

一行文本用 Input,更多内容用 Textarea:

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

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

<Field>
  <FieldLabel>Department</FieldLabel>
  <FieldControl name="department">
    {#snippet render({ props })}
      <select {...props}>
        <option value="design">Design</option>
        <option value="engineering">Engineering</option>
      </select>
    {/snippet}
  </FieldControl>
</Field>

字段里的 Checkbox、Switch 或 Radio Group 会使用字段的标签和描述。按压标签会切换复选框或开关。单选组会把字段的标签当作自己的名称,每个单选项则保留自己的标签:

<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" defaultValue="monthly">
    <label>
      <Radio value="monthly" />
      Monthly
    </label>
    <label>
      <Radio value="yearly" />
      Yearly
    </label>
  </RadioGroup>
</Field>

校验

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

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

控制台
<script lang="ts">
  import {
    Field,
    FieldDescription,
    FieldError,
    FieldLabel,
  } from "@ui-sdk/svelte/field"
  import { Input } from "@ui-sdk/svelte/input"
  import { useLog } from "./log"

  const log = useLog()

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

<form data-slot="stack" onsubmit={submit}>
  <Field name="email">
    <FieldLabel>Email</FieldLabel>
    <Input type="email" required placeholder="hollis@example.com" />
    <FieldDescription>
      {#snippet children(state)}
        {state.valid ? "Looks good." : "We'll send you a confirmation link."}
      {/snippet}
    </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>
在邮箱为空或无效时点击 Subscribe,然后改正它来清除错误。

来自你的代码的错误

当服务器或表单库给出错误时,传入 invalid。true 会立即显示它。清除值即可回到浏览器的校验。

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

<Field name="email" invalid={serverError ? true : undefined}>
  <FieldLabel>Email</FieldLabel>
  <Input type="email" required onValueChange={() => (serverError = null)} />
  <FieldError match="valueMissing">Enter your email address.</FieldError>
  {#if serverError}
    <FieldError match>{serverError}</FieldError>
  {/if}
</Field>

必填与禁用

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

禁用的字段会禁用它的控件,并给每个部件标记 data-disabled,就像禁用的字段集对它里面的每个字段所做的那样。

字符计数

把文本放在状态里,并在描述里显示它的长度。在控件上设置 maxlength,让这个限制生效。

<Field>
  <FieldLabel>Bio</FieldLabel>
  <Textarea bind:value={bio} maxlength={280} />
  <FieldDescription>{bio.length} / 280</FieldDescription>
</Field>

表单

控件用自己的 name 提交它的值;没有 name 时,就用字段的 name。重置会恢复控件的默认值,并隐藏校验错误。禁用的控件不会包含在提交的值里。共享的表单行为见表单。

字段集

字段集把相关的字段归到一个图例(legend)下,并一起禁用它们。

<script lang="ts">
  import {
    Field,
    FieldDescription,
    FieldGroup,
    FieldLabel,
    FieldLegend,
    FieldSet,
  } from "@ui-sdk/svelte/field"
  import { Input } from "@ui-sdk/svelte/input"
</script>

<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>
在地址字段之间移动。它们的图例和描述为这个分组命名。

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

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

禁用字段集

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

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

字段集里的分组

图例会为字段集里的复选框组或单选组命名,所以分组不需要自己的标签。

<FieldSet>
  <FieldLegend>Notifications</FieldLegend>
  <CheckboxGroup name="notify" defaultValue={["mentions"]}>
    <label>
      <Checkbox value="mentions" />
      Mentions
    </label>
    <label>
      <Checkbox value="follows" />
      New followers
    </label>
  </CheckboxGroup>
</FieldSet>

自定义渲染

每个部件都接受 render snippet,用来在原地渲染别的元素或组件,比如 FieldControl 的 <select>。它会收到要展开的 props 和字段的状态:

<FieldDescription>
  {#snippet render({ props, state })}
    <p {...props}>
      {state.invalid ? "Use letters and numbers only." : "Letters and numbers."}
    </p>
  {/snippet}
</FieldDescription>

children snippet 也会收到状态。FieldError 的状态里还有当前问题的 message。

状态是惰性读取的。只有当部件的渲染函数或槽位读过某个值时,这个值的变化才会让部件重新渲染。每个部件的状态列在状态下。

自定义控件

useFieldControl 让你自己的控件像我们的控件一样加入它周围的字段。在字段之外,它返回 null。在字段之内,它返回:

  • name():字段的 name,供没有自己设置 name 的控件使用。
  • disabled():字段是否被禁用。
  • control(id, describedBy):在脚本里调用一次,传入控件自己的 id 和 aria-describedby 的 getter。你的描述在前,字段的在后。它返回一个函数,把字段的属性合并进控件的 props:id、aria-labelledby、aria-describedby、aria-invalid、disabled 和字段的数据属性,以及告诉字段哪个元素是它控件的 attachment。控件保留自己的 data-slot。

在标记里展开合并后的 props,这样字段变化时控件会更新,比如它的标签或错误出现时。

<script lang="ts">
  import { useFieldControl } from "@ui-sdk/svelte/field"
  import type { SvelteHTMLElements } from "svelte/elements"

  let { ...rest }: SvelteHTMLElements["input"] = $props()

  const field = useFieldControl()
  const control = field?.control(
    () => rest.id,
    () => rest["aria-describedby"]
  )
  const input = $derived({
    type: "tel",
    autocomplete: "tel" as const,
    name: field?.name(),
    ...rest,
    "data-slot": "phone-input",
  })
</script>

<input {...control ? control(input) : input} />
<Field>
  <FieldLabel>Phone</FieldLabel>
  <PhoneInput required />
  <FieldError />
</Field>

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

想用我们的控件所用的原语(primitive)从零构建控件,请参阅原语。

样式

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

每个部件都有一个 data-slot,比如 field-label,它的状态属性列在数据属性下。

数据属性

Field

[data-slot="field"]

属性含义
data-disabledPresent when the field is disabled.
data-invalidPresent while the field shows as invalid: with invalid, or once a submit finds the control invalid.

FieldLabel

[data-slot="field-label"]

属性含义
data-disabledPresent when the field is disabled.
data-invalidPresent while the field shows as invalid: with invalid, or once a submit finds the control invalid.

FieldControl

[data-slot="field-control"]

属性含义
data-disabledPresent when the field is disabled.
data-invalidPresent while the field shows as invalid: with invalid, or once a submit finds the control invalid.

FieldDescription

[data-slot="field-description"]

属性含义
data-disabledPresent when the field is disabled.
data-invalidPresent while the field shows as invalid: with invalid, or once a submit finds the control invalid.

FieldError

[data-slot="field-error"]

属性含义
data-disabledPresent when the field is disabled.
data-invalidPresent 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-disabledPresent when the field set is disabled, by its own prop or a <fieldset> around it.

FieldLegend

[data-slot="field-legend"]

属性含义
data-disabledPresent when the field set is disabled, by its own prop or a <fieldset> around it.

FieldSet 里的 FieldDescription

[data-slot="field-description"]

属性含义
data-disabledPresent when the field set is disabled, by its own prop or a <fieldset> around it.

API 参考

属性与下面相同,都作为 Svelte props 传入。

字段没有变更事件。从部件的数据属性或渲染函数里读取它的状态。设置 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.

状态

disabledboolean
Whether the field is disabled, by itself or by a <fieldset>.
requiredboolean
Whether the control is required, read from its required or aria-required.
focusedboolean
Whether focus is inside the control.
invalidboolean
Whether the field shows as invalid: invalid when you pass it, else the browser's validation once shown.
validboolean
Whether the browser's validation passes, once shown. Always false while you pass invalid.
disabledboolean
Whether the field is disabled, by itself or by a <fieldset>.
requiredboolean
Whether the control is required, read from its required or aria-required.
focusedboolean
Whether focus is inside the control.
invalidboolean
Whether the field shows as invalid: invalid when you pass it, else the browser's validation once shown.
validboolean
Whether the browser's validation passes, once shown. Always false while you pass invalid.
messagestring
The browser's message for the current problem. Children you pass show instead.

FieldDescription 会收到字段的状态;当它描述字段集时,只收到 disabled。

disabledboolean
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>.
requiredboolean | undefined
Whether the control is required, read from its required or aria-required.
focusedboolean | undefined
Whether focus is inside the control.
invalidboolean | undefined
Whether the field shows as invalid: invalid when you pass it, else the browser's validation once shown.
validboolean | undefined
Whether the browser's validation passes, once shown. Always false while you pass invalid.

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

disabledboolean
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 运行。
  • A hidden error outside a field stays hidden whatever display its class gives. 仅在 Web components 运行。
  • An error outside a field follows its match. 仅在 Web components 运行。
  • An error outside a field shows a child that arrives after it. 仅在 Web components 运行。
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 运行。
  • 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.

运行于 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.

运行于 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.

运行于 React、Vue 和 web components。