# OTP Input

输入一次性验证码，支持粘贴、自动填充和原生表单校验。

用 OTP Input 输入短信或邮件发来的短验证码，比如登录验证码或校验码。每个字符都有自己的槽位，粘贴或自动填充的验证码会一次填满所有槽位。

```vue title="basic.vue"
<script setup lang="ts">
import { MinusIcon } from "@lucide/vue"
import { Field, FieldLabel } from "@ui-sdk/vue/field"
import {
  OTPInput,
  OTPInputGroup,
  OTPInputSeparator,
  OTPInputSlot,
} from "@ui-sdk/vue/otp-input"
</script>

<template>
  <Field>
    <FieldLabel>Verification code</FieldLabel>
    <OTPInput :max-length="6">
      <OTPInputGroup>
        <OTPInputSlot :index="0" />
        <OTPInputSlot :index="1" />
        <OTPInputSlot :index="2" />
      </OTPInputGroup>
      <OTPInputSeparator>
        <MinusIcon aria-hidden="true" />
      </OTPInputSeparator>
      <OTPInputGroup>
        <OTPInputSlot :index="3" />
        <OTPInputSlot :index="4" />
        <OTPInputSlot :index="5" />
      </OTPInputGroup>
    </OTPInput>
  </Field>
</template>
```

输入六位验证码，或粘贴 123-456。点击一个槽位可以编辑它，用方向键移动，用你常用的撤销快捷键撤销一次修改。

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

## 组合
用下面的组合构建 `OTPInput`：

```text
OTPInput
└── OTPInputGroup
    ├── OTPInputSlot
    └── OTPInputSlot
```

`OTPInput` 创建原生输入框并保存验证码。`OTPInputGroup` 排布一连串槽位。每个 `OTPInputSlot` 显示它在从 0 开始的 `index` 处的字符。当验证码分段更易读时，在组之间加上 `OTPInputSeparator`，比如上面示例里的短横线。

组和分隔符只改变同一个值的呈现方式。它们不会创建额外的字段或 Tab 停靠点：这些槽位显示的是单个原生输入框的值，由它处理选择、粘贴、撤销、表单提交和自动填充。它使用 `autocomplete="one-time-code"`，让支持的浏览器和密码管理器可以提供已保存或刚收到的验证码。

## 用法
导入部件并把它们组合起来：

```vue
<script setup lang="ts">
import { OTPInput, OTPInputGroup, OTPInputSlot } from "@ui-sdk/vue/otp-input"
</script>

<template>
  <OTPInput :max-length="4" aria-label="Verification code">
    <OTPInputGroup>
      <OTPInputSlot :index="0" />
      <OTPInputSlot :index="1" />
      <OTPInputSlot :index="2" />
      <OTPInputSlot :index="3" />
    </OTPInputGroup>
  </OTPInput>
</template>
```

## 四位数字
把 `max-length` 设为验证码的长度，并渲染同样多的槽位。默认长度是六位。

```vue title="four-digits.vue"
<script setup lang="ts">
import { Field, FieldLabel } from "@ui-sdk/vue/field"
import { OTPInput, OTPInputGroup, OTPInputSlot } from "@ui-sdk/vue/otp-input"
</script>

<template>
  <Field>
    <FieldLabel>PIN</FieldLabel>
    <OTPInput :max-length="4" text-align="center">
      <OTPInputGroup>
        <OTPInputSlot
          v-for="index in [0, 1, 2, 3]"
          :key="index"
          :index="index"
        />
      </OTPInputGroup>
    </OTPInput>
  </Field>
</template>
```

在 PIN 里输入四位数字。填满之后，再输入一位数字会替换选中的槽位。点击另一个槽位可以编辑它。

## 字母与数字
把 `pattern` 设为 `digits`、`letters` 或 `alphanumeric`。默认是 `digits`。模式会过滤字符，并在触摸设备上选择合适的键盘。

```vue title="alphanumeric.vue"
<script setup lang="ts">
import { MinusIcon } from "@lucide/vue"
import { Field, FieldLabel } from "@ui-sdk/vue/field"
import {
  OTPInput,
  OTPInputGroup,
  OTPInputSeparator,
  OTPInputSlot,
} from "@ui-sdk/vue/otp-input"
</script>

<template>
  <Field>
    <FieldLabel>Recovery code</FieldLabel>
    <OTPInput :max-length="8" pattern="alphanumeric">
      <OTPInputGroup>
        <OTPInputSlot
          v-for="index in [0, 1, 2, 3]"
          :key="index"
          :index="index"
        />
      </OTPInputGroup>
      <OTPInputSeparator>
        <MinusIcon aria-hidden="true" />
      </OTPInputSeparator>
      <OTPInputGroup>
        <OTPInputSlot
          v-for="index in [4, 5, 6, 7]"
          :key="index"
          :index="index"
        />
      </OTPInputGroup>
    </OTPInput>
  </Field>
</template>
```

在 Recovery code 里输入字母和数字，或粘贴 ab12-cd34。连字符会被移除，八个字符会填满槽位。

## 自定义模式
传入正则表达式，比如 `/[0-9A-F]/i`，来接受十六进制字符。用 `input-mode` 单独选择键盘。示例以大写显示字母，但不改变存储的大小写。

```vue title="pattern.vue"
<script setup lang="ts">
import { Field, FieldLabel } from "@ui-sdk/vue/field"
import { OTPInput, OTPInputGroup, OTPInputSlot } from "@ui-sdk/vue/otp-input"
</script>

<template>
  <Field>
    <FieldLabel>Device code</FieldLabel>
    <OTPInput :max-length="6" :pattern="/[0-9A-F]/i" input-mode="text">
      <OTPInputGroup>
        <OTPInputSlot
          v-for="index in [0, 1, 2, 3, 4, 5]"
          :key="index"
          :index="index"
        />
      </OTPInputGroup>
    </OTPInput>
  </Field>
</template>
```

试着在 Device code 里输入 12zzab。z 字符会被拒绝；接受的值是 12ab，显示为 12AB。

## 校验
在 [Field](/docs/vue/components/field) 里，当你的代码拒绝这个值时传入 `invalid`，比如服务器没有接受的验证码。字段会用 `aria-invalid` 标记输入框，并关联它的 `FieldError`。在字段之外，需要你自己传入 `aria-invalid` 和 `aria-describedby`。

```vue title="invalid.vue"
<script setup lang="ts">
import { Field, FieldError, FieldLabel } from "@ui-sdk/vue/field"
import { OTPInput, OTPInputGroup, OTPInputSlot } from "@ui-sdk/vue/otp-input"
import { ref } from "vue"

const invalid = ref(true)
</script>

<template>
  <Field :invalid="invalid">
    <FieldLabel>Verification code</FieldLabel>
    <OTPInput default-value="482913" @value-change="invalid = false">
      <OTPInputGroup>
        <OTPInputSlot
          v-for="index in [0, 1, 2, 3, 4, 5]"
          :key="index"
          :index="index"
        />
      </OTPInputGroup>
    </OTPInput>
    <FieldError>That code has expired. Request a new one.</FieldError>
  </Field>
</template>
```

Verification code 被标记为无效，下面的错误说明了原因。编辑任意一位数字即可清除错误。

## 受控
用 `v-model:value` 绑定验证码。`@value-change` 还会收到变更详情。在变更回调里调用 `details.cancel()` 来拒绝一次变更。传入的值会像输入的值一样，按模式过滤，并限制在 `max-length` 以内。

```vue title="controlled.vue"
<script setup lang="ts">
import { Field, FieldLabel } from "@ui-sdk/vue/field"
import { OTPInput, OTPInputGroup, OTPInputSlot } from "@ui-sdk/vue/otp-input"
import { ref } from "vue"
import { useLog } from "./log"

const log = useLog()
const value = ref("")
</script>

<template>
  <Field>
    <FieldLabel>One-time password</FieldLabel>
    <OTPInput
      v-model:value="value"
      @value-change="
        (next, details) => log(`${next || 'Empty'} (${details.reason})`)
      "
    >
      <OTPInputGroup>
        <OTPInputSlot
          v-for="index in [0, 1, 2, 3, 4, 5]"
          :key="index"
          :index="index"
        />
      </OTPInputGroup>
    </OTPInput>
  </Field>
</template>
```

在 One-time password 里输入、粘贴或删除数字。控制台会记录每个新验证码和它的原因。

受控状态的通用约定见[状态与事件](/docs/vue/state-and-events)。[原因](https://ui-sdk.cn/docs/vue/components/otp-input#reasons)区分输入、粘贴、撤销和控制器动作。

## 填满时
`@value-commit` 会在一次变更填满所有槽位时运行，包括输入、粘贴、自动填充和控制器写入。修改已经填满的验证码会再次运行它。表单重置和页面恢复不会。

```vue title="complete.vue"
<script setup lang="ts">
import { Field, FieldLabel } from "@ui-sdk/vue/field"
import { OTPInput, OTPInputGroup, OTPInputSlot } from "@ui-sdk/vue/otp-input"
import { useLog } from "./log"

const log = useLog()
</script>

<template>
  <Field>
    <FieldLabel>Verification code</FieldLabel>
    <OTPInput
      @value-commit="
        (value, details) => log(`Checking ${value} (${details.reason})`)
      "
    >
      <OTPInputGroup>
        <OTPInputSlot
          v-for="index in [0, 1, 2, 3, 4, 5]"
          :key="index"
          :index="index"
        />
      </OTPInputGroup>
    </OTPInput>
  </Field>
</template>
```

填满全部六个槽位。控制台会记录完整的验证码和变更原因。替换一位数字会再次记录；删除一位则不会记录。

## 表单
设置 `name`，让验证码进入 `FormData`。`required` 会阻止空验证码，不完整的验证码无法通过长度校验。重置会恢复默认值。用 `form` 把表单外的控件关联到表单的 ID。

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

const log = useLog()

function onSubmit(event: Event) {
  const data = [...new FormData(event.currentTarget as HTMLFormElement)].map(
    ([name, value]) => `${name}=${value}`
  )
  log(`Submitted ${data.join(", ")}`)
}
</script>

<template>
  <div data-slot="stack">
    <form id="verify-sign-in" @submit.prevent="onSubmit">
      <Field>
        <FieldLabel>Verification code</FieldLabel>
        <OTPInput name="code" required>
          <OTPInputGroup>
            <OTPInputSlot
              v-for="index in [0, 1, 2, 3, 4, 5]"
              :key="index"
              :index="index"
            />
          </OTPInputGroup>
        </OTPInput>
        <FieldDescription
          >Enter the six-digit code we sent to
          hollis@example.com.</FieldDescription
        >
        <FieldError />
      </Field>
    </form>
    <Field>
      <FieldLabel>Recovery code (optional)</FieldLabel>
      <OTPInput
        name="recovery"
        form="verify-sign-in"
        :max-length="8"
        pattern="alphanumeric"
      >
        <OTPInputGroup>
          <OTPInputSlot
            v-for="index in [0, 1, 2, 3, 4, 5, 6, 7]"
            :key="index"
            :index="index"
          />
        </OTPInputGroup>
      </OTPInput>
      <FieldError />
    </Field>
    <div data-slot="row">
      <button type="reset" form="verify-sign-in">Reset</button>
      <button type="submit" form="verify-sign-in" data-variant="solid">
        Verify
      </button>
    </div>
  </div>
</template>
```

在验证码为空或不完整时选择 Verify，查看校验效果。输入全部六位数字，然后选择 Verify，让控制台记录表单值。Recovery code 位于表单之外，但会随表单一起提交。Reset 会清空两个字段。

输入的不完整验证码会报告 `tooShort`。不完整的默认值和控制器写入会通过原生输入框的模式检查，因为浏览器不会对这些值应用 minlength 校验。

## 禁用与只读
禁用的输入框无法聚焦、更改或提交。`read-only` 阻止更改，同时让输入框保持可聚焦，并保留在表单数据里。

```vue
<OTPInput disabled default-value="123456" aria-label="Disabled code">
  ...
</OTPInput>
<OTPInput read-only default-value="654321" aria-label="Read-only code">
  ...
</OTPInput>
```

## 控制器
用 `createOTPInputController()` 创建一个控制器，并作为 `controller` 传入，以便从另一个控件读取、填充、清空或聚焦输入框。写入使用 `imperative` 原因，并像输入一样经过相同的过滤和变更回调。

```vue
<script setup lang="ts">
const code = createOTPInputController()
</script>

<template>
  <button @click="code.setValue('123456')">Fill</button>
  <button @click="code.clear()">Clear</button>
  <button @click="console.log(code.getValue())">Read</button>
  <button @click="code.focus()">Focus</button>
  <OTPInput :controller="code" aria-label="Verification code"> ... </OTPInput>
</template>
```

[控制器](/docs/vue/controllers)介绍了创建和共享控制器。

## 自定义渲染
根的状态暴露所有 `slots`。如果你想自己绘制槽位的内容，每个槽位会暴露 `char`、`active` 和 `hasFakeCaret`。渲染约定见[部件与组合](/docs/vue/parts-and-composition)。

## 样式
用 `data-active` 和 `data-fake-caret` 绘制活动的槽位和光标。示例包含光标动画，并在用户偏好减少动态效果时禁用动画。让每个槽位保持 `position: relative`，这样它的光标会留在槽位内部。

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

## 数据属性
### OTPInput
`[data-slot="otp-input"]`

- `data-complete`: Present while every slot is filled.
- `data-filled`: Present while the code holds any character.
- `data-disabled`: Present when disabled, by its own prop or a `<fieldset>`.
- `data-focused`: Present while the input has focus.

### OTPInputGroup
`[data-slot="otp-input-group"]`

- `data-complete`: Present while every slot is filled.
- `data-filled`: Present while the code holds any character.
- `data-disabled`: Present when disabled, by its own prop or a `<fieldset>`.
- `data-focused`: Present while the input has focus.

### OTPInputSlot
`[data-slot="otp-input-slot"]`

- `data-filled`: Present while the slot holds a character.
- `data-disabled`: Present when disabled, by its own prop or a `<fieldset>`.
- `data-active`: Present on the slot typing goes to: the selected character, or the empty slot after the last one. Only while focused.
- `data-fake-caret`: Present on the active slot while it's empty. Draw a blinking caret in it; the input's own caret is hidden.

### OTPInputSeparator
`[data-slot="otp-input-separator"]`

- `data-disabled`: Present when disabled, by its own prop or a `<fieldset>`.

## API 参考
Props 与下面相同，回调是事件。`id`、`autofocus`、`aria-label`、`aria-labelledby`、`aria-describedby` 和 `aria-invalid` 会传到输入框上。

### OTPInput
- `debug?` (`boolean`): Logs every state change with its reason to the console, in development builds.
- `value?` (`string`): The code, for a controlled input.
- `defaultValue?` (`string`): The code it starts with, when uncontrolled. A form reset returns here.
- `@value-change` (`((value: string, details: ChangeDetails<OTPInputValueChangeReason>) => void)`): Runs when the code changes: typing or deleting (`"input-change"`), a paste (`"paste"`), the browser's undo and redo, a form reset, or a controller. Autofill and codes from the keyboard's suggestions are `"input-change"`. `details.cancel()` keeps the code as it was.
- `@value-commit` (`((value: string, details: CommitDetails<OTPInputValueChangeReason>) => void)`): Runs when a change fills every slot, with the whole code, like to verify it. A controller filling it counts, so does a code that changes while full.
- `maxLength?` (`number`): How many characters the code has, one slot each.
- `pattern?` (`OTPInputPattern`): Which characters it accepts: `"digits"`, `"letters"`, `"alphanumeric"`, or a regular expression each character must match, like `/[A-F0-9]/i`. Anything else typed, pasted or dropped is ignored.
- `inputMode?` (`"decimal" | "none" | "numeric" | "tel" | "text"`): The keyboard touch screens show.
- `textAlign?` (`"center" | "end" | "start"`): Where the invisible input keeps its text and caret. It decides where the browser puts its own popups, like the paste menu on phones. `"start"` and `"end"` follow the reading direction.
- `autoComplete?` (`string`): The input's `autocomplete`. `"one-time-code"` lets phones offer a code from a message, and password managers fill it.
- `disabled?` (`boolean`): Disables it like a native input: it can't be focused, and isn't submitted.
- `readOnly?` (`boolean`): Makes it read-only: focusable and submitted, but the code can't change.
- `required?` (`boolean`): Requires a code before the form submits. A partial code is too short either way.
- `name?` (`string`): The name it submits the code under.
- `form?` (`string`): The id of a form to belong to, when it isn't inside that form.
- `controller?` (`{ getValue: () => string; setValue: (value: string, options?: OTPInputChangeOptions) => boolean; clear: (options?: OTPInputChangeOptions) => boolean; focus: () => void; }`): Reads and writes the code from anywhere. Create one with `createOTPInputController()`.

### OTPInputSlot
- `index` (`number`): Which character of the code the slot shows, from 0.

### 状态
渲染函数、基于状态的类名和槽位会收到什么。根、组和分隔符会收到输入框的状态。

- `value` (`string`): The code.
- `slots` (`OTPInputSlotData[]`): One entry per slot: its character, whether it's active, and whether it draws a caret.
- `focused` (`boolean`): Whether the input has focus.
- `complete` (`boolean`): Whether every slot is filled.
- `disabled` (`boolean`): Whether it's disabled, by itself or by a `<fieldset>`.

槽位会收到自己的状态：

- `char` (`string | null`): The character in the slot, or null when it's empty.
- `active` (`boolean`): Whether the slot is where typing goes: the selected character, or the empty slot after the last one.
- `hasFakeCaret` (`boolean`): Whether the slot should draw a caret: it's active and empty. The real caret is hidden.
- `index` (`number`): Which character of the code the slot shows.
- `focused` (`boolean`): Whether the input has focus.
- `disabled` (`boolean`): Whether it's disabled, by itself or by a `<fieldset>`.

### 原因
`details.reason` 说明验证码为什么改变。自动填充和来自键盘建议的验证码是 `input-change`。

- `input-change` (`Event`): Typing, pasting or dropping changed a text field's value; in a combobox it can also open or close it, or Enter keeps the typed text as the value.
- `paste` (`ClipboardEvent`): Files were pasted, like a screenshot, or text and tokens into a token input.
- `undo` (`KeyboardEvent | InputEvent`): Undo, from the keyboard, the Edit menu or a controller.
- `redo` (`KeyboardEvent | InputEvent`): Redo, from the keyboard, the Edit menu or a controller.
- `reset` (`none`): A form reset.
- `restore` (`none`): The browser restored state, like after going back, or a saved value was read back from storage.
- `imperative` (`none`): A controller or `api` call.

### 控制器
用 `createOTPInputController()` 创建一个，并作为 `controller` 传入。

`setValue()` 和 `clear()` 接受可选的 `{ reason, event }`，并像输入一样运行变更回调。

- `getValue()` (`() => string`): The code.
- `setValue(value, options?)` (`(value: string, options?: OTPInputChangeOptions | undefined) => boolean`): Sets the code, as typing it would. Characters that don't fit the pattern are dropped. Returns false when the change was canceled or nothing changed.
- `clear(options?)` (`(options?: OTPInputChangeOptions | undefined) => boolean`): Empties the code. Returns false when the change was canceled or nothing changed.
- `focus()` (`() => void`): Moves focus to the input.

### 事件
事件先收到验证码，然后收到变更详情。只有变更事件没有被取消时，`v-model` 才会更新。

| Binding         | 所属部件   | 收到                                           |
| --------------- | ---------- | ---------------------------------------------- |
| `v-model:value` | `OTPInput` | 验证码                                         |
| `@value-change` | `OTPInput` | `(value, details)`：新验证码和[原因](https://ui-sdk.cn/docs/vue/components/otp-input#reasons) |
| `@value-commit` | `OTPInput` | `(value, details)`：完整的验证码和填满它的原因 |

## 无障碍
用 FieldLabel、原生 label、`aria-label` 或 `aria-labelledby` 给输入框一个无障碍名称。屏幕阅读器只会遇到一个包含完整验证码的输入框；可见的槽位、组和分隔符对它们隐藏。

### 键盘
输入框保留原生的按键行为。方向键、Home 和 End 在槽位之间移动选择，Backspace 删除，你常用的快捷键可以撤销和重做。粘贴 `123-456` 这样的验证码会移除分隔符。

### 经过测试的行为
下面每一行都是一个自动化测试。

- Typing fills the slots in order.
- Characters the pattern doesn't accept are ignored.
- Filling every slot completes the code.
- Backspace deletes the last character.
- ArrowLeft goes back a slot, and typing replaces its character.
- Pressing a filled slot lets you retype it.
- Pasting a code with a dash fills every slot.
- The form submits the code under its name.
- A partial default code is too short to submit.
- A typed partial code is too short, not the wrong format.
- A canceled change keeps the code.
- A disabled code can't be typed into.
- A code of letters and digits takes both.
- The input asks for a one-time code and a numeric keyboard.
- Typing a whole code with no waits fills it.

Runs in React、Vue 和 web components.
