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

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

"use client"

import { Field, FieldLabel } from "@ui-sdk/react/field"
import {
  OTPInput,
  OTPInputGroup,
  OTPInputSeparator,
  OTPInputSlot,
} from "@ui-sdk/react/otp-input"
import { MinusIcon } from "lucide-react"

function Example() {
  return (
    <Field>
      <FieldLabel>Verification code</FieldLabel>
      <OTPInput maxLength={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>
  )
}

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

安装

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

组合

用下面的组合构建 OTPInput:

OTPInput
└── OTPInputGroup
    ├── OTPInputSlot
    └── OTPInputSlot

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

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

用法

导入部件并把它们组合起来:

import { OTPInput, OTPInputGroup, OTPInputSlot } from "@ui-sdk/react/otp-input"

function Example() {
  return (
    <OTPInput maxLength={4} aria-label="Verification code">
      <OTPInputGroup>
        <OTPInputSlot index={0} />
        <OTPInputSlot index={1} />
        <OTPInputSlot index={2} />
        <OTPInputSlot index={3} />
      </OTPInputGroup>
    </OTPInput>
  )
}

export { Example }

四位数字

把 maxLength 设为验证码的长度,并渲染同样多的槽位。默认长度是六位。

"use client"

import { Field, FieldLabel } from "@ui-sdk/react/field"
import { OTPInput, OTPInputGroup, OTPInputSlot } from "@ui-sdk/react/otp-input"

function Example() {
  return (
    <Field>
      <FieldLabel>PIN</FieldLabel>
      <OTPInput maxLength={4} textAlign="center">
        <OTPInputGroup>
          {[0, 1, 2, 3].map((index) => (
            <OTPInputSlot key={index} index={index} />
          ))}
        </OTPInputGroup>
      </OTPInput>
    </Field>
  )
}

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

字母与数字

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

"use client"

import { Field, FieldLabel } from "@ui-sdk/react/field"
import {
  OTPInput,
  OTPInputGroup,
  OTPInputSeparator,
  OTPInputSlot,
} from "@ui-sdk/react/otp-input"
import { MinusIcon } from "lucide-react"

function Example() {
  return (
    <Field>
      <FieldLabel>Recovery code</FieldLabel>
      <OTPInput maxLength={8} pattern="alphanumeric">
        <OTPInputGroup>
          {[0, 1, 2, 3].map((index) => (
            <OTPInputSlot key={index} index={index} />
          ))}
        </OTPInputGroup>
        <OTPInputSeparator>
          <MinusIcon aria-hidden="true" />
        </OTPInputSeparator>
        <OTPInputGroup>
          {[4, 5, 6, 7].map((index) => (
            <OTPInputSlot key={index} index={index} />
          ))}
        </OTPInputGroup>
      </OTPInput>
    </Field>
  )
}

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

自定义模式

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

"use client"

import { Field, FieldLabel } from "@ui-sdk/react/field"
import { OTPInput, OTPInputGroup, OTPInputSlot } from "@ui-sdk/react/otp-input"

function Example() {
  return (
    <Field>
      <FieldLabel>Device code</FieldLabel>
      <OTPInput maxLength={6} pattern={/[0-9A-F]/i} inputMode="text">
        <OTPInputGroup>
          {[0, 1, 2, 3, 4, 5].map((index) => (
            <OTPInputSlot key={index} index={index} />
          ))}
        </OTPInputGroup>
      </OTPInput>
    </Field>
  )
}

export { Example }
试着在 Device code 里输入 12zzab。z 字符会被拒绝;接受的值是 12ab,显示为 12AB。

校验

在 Field 里,当你的代码拒绝这个值时传入 invalid,比如服务器没有接受的验证码。字段会用 aria-invalid 标记输入框,并关联它的 FieldError。在字段之外,需要你自己传入 aria-invalid 和 aria-describedby。

"use client"

import { Field, FieldError, FieldLabel } from "@ui-sdk/react/field"
import { OTPInput, OTPInputGroup, OTPInputSlot } from "@ui-sdk/react/otp-input"
import * as React from "react"

function Example() {
  const [invalid, setInvalid] = React.useState(true)

  return (
    <Field invalid={invalid}>
      <FieldLabel>Verification code</FieldLabel>
      <OTPInput defaultValue="482913" onValueChange={() => setInvalid(false)}>
        <OTPInputGroup>
          {[0, 1, 2, 3, 4, 5].map((index) => (
            <OTPInputSlot key={index} index={index} />
          ))}
        </OTPInputGroup>
      </OTPInput>
      <FieldError>That code has expired. Request a new one.</FieldError>
    </Field>
  )
}

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

受控

传入 value,并在 onValueChange 里更新它。在变更回调里调用 details.cancel() 来拒绝一次变更。传入的值会像输入的值一样,按模式过滤,并限制在 maxLength 以内。

控制台
"use client"

import { Field, FieldLabel } from "@ui-sdk/react/field"
import { OTPInput, OTPInputGroup, OTPInputSlot } from "@ui-sdk/react/otp-input"
import * as React from "react"
import { useLog } from "./log"

function Example() {
  const log = useLog()
  const [value, setValue] = React.useState("")

  return (
    <Field>
      <FieldLabel>One-time password</FieldLabel>
      <OTPInput
        value={value}
        onValueChange={(value, details) => {
          setValue(value)
          log(`${value || "Empty"} (${details.reason})`)
        }}
      >
        <OTPInputGroup>
          {[0, 1, 2, 3, 4, 5].map((index) => (
            <OTPInputSlot key={index} index={index} />
          ))}
        </OTPInputGroup>
      </OTPInput>
    </Field>
  )
}

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

受控状态的通用约定见状态与事件。原因区分输入、粘贴、撤销和控制器动作。

填满时

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

控制台
"use client"

import { Field, FieldLabel } from "@ui-sdk/react/field"
import { OTPInput, OTPInputGroup, OTPInputSlot } from "@ui-sdk/react/otp-input"
import { useLog } from "./log"

function Example() {
  const log = useLog()

  return (
    <Field>
      <FieldLabel>Verification code</FieldLabel>
      <OTPInput
        onValueCommit={(value, details) =>
          log(`Checking ${value} (${details.reason})`)
        }
      >
        <OTPInputGroup>
          {[0, 1, 2, 3, 4, 5].map((index) => (
            <OTPInputSlot key={index} index={index} />
          ))}
        </OTPInputGroup>
      </OTPInput>
    </Field>
  )
}

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

表单

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

控制台
"use client"

import {
  Field,
  FieldDescription,
  FieldError,
  FieldLabel,
} from "@ui-sdk/react/field"
import { OTPInput, OTPInputGroup, OTPInputSlot } from "@ui-sdk/react/otp-input"
import { useLog } from "./log"

function Example() {
  const log = useLog()

  return (
    <div data-slot="stack">
      <form
        id="verify-sign-in"
        onSubmit={(event) => {
          event.preventDefault()
          const data = [...new FormData(event.currentTarget)].map(
            ([name, value]) => `${name}=${value}`
          )
          log(`Submitted ${data.join(", ")}`)
        }}
      >
        <Field>
          <FieldLabel>Verification code</FieldLabel>
          <OTPInput name="code" required>
            <OTPInputGroup>
              {[0, 1, 2, 3, 4, 5].map((index) => (
                <OTPInputSlot 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"
          maxLength={8}
          pattern="alphanumeric"
        >
          <OTPInputGroup>
            {[0, 1, 2, 3, 4, 5, 6, 7].map((index) => (
              <OTPInputSlot 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>
  )
}

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

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

禁用与只读

禁用的输入框无法聚焦、更改或提交。readOnly 阻止更改,同时让输入框保持可聚焦,并保留在表单数据里。

<OTPInput disabled defaultValue="123456" aria-label="Disabled code">
  ...
</OTPInput>
<OTPInput readOnly defaultValue="654321" aria-label="Read-only code">
  ...
</OTPInput>

控制器

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

const [code] = React.useState(() => createOTPInputController())

<button onClick={() => code.setValue("123456")}>Fill</button>
<button onClick={() => code.clear()}>Clear</button>
<button onClick={() => console.log(code.getValue())}>Read</button>
<button onClick={() => code.focus()}>Focus</button>
<OTPInput controller={code} aria-label="Verification code">
  ...
</OTPInput>

控制器介绍了创建和共享控制器。

自定义渲染

根的状态暴露所有 slots。如果你想自己绘制槽位的内容,每个槽位会暴露 char、active 和 hasFakeCaret。渲染约定见部件与组合。

样式

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

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

数据属性

OTPInput

[data-slot="otp-input"]

属性含义
data-completePresent while every slot is filled.
data-filledPresent while the code holds any character.
data-disabledPresent when disabled, by its own prop or a <fieldset>.
data-focusedPresent while the input has focus.

OTPInputGroup

[data-slot="otp-input-group"]

属性含义
data-completePresent while every slot is filled.
data-filledPresent while the code holds any character.
data-disabledPresent when disabled, by its own prop or a <fieldset>.
data-focusedPresent while the input has focus.

OTPInputSlot

[data-slot="otp-input-slot"]

属性含义
data-filledPresent while the slot holds a character.
data-disabledPresent when disabled, by its own prop or a <fieldset>.
data-activePresent on the slot typing goes to: the selected character, or the empty slot after the last one. Only while focused.
data-fake-caretPresent 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-disabledPresent when disabled, by its own prop or a <fieldset>.

API 参考

Props 和回调与下面相同,作为 React 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.
onValueChange?((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.
onValueCommit?((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

indexnumber
Which character of the code the slot shows, from 0.

状态

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

valuestring
The code.
slotsOTPInputSlotData[]
One entry per slot: its character, whether it's active, and whether it draws a caret.
focusedboolean
Whether the input has focus.
completeboolean
Whether every slot is filled.
disabledboolean
Whether it's disabled, by itself or by a <fieldset>.

槽位会收到自己的状态:

charstring | null
The character in the slot, or null when it's empty.
activeboolean
Whether the slot is where typing goes: the selected character, or the empty slot after the last one.
hasFakeCaretboolean
Whether the slot should draw a caret: it's active and empty. The real caret is hidden.
indexnumber
Which character of the code the slot shows.
focusedboolean
Whether the input has focus.
disabledboolean
Whether it's disabled, by itself or by a <fieldset>.

原因

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

input-changeEvent
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.
pasteClipboardEvent
Files were pasted, like a screenshot, or text and tokens into a token input.
undoKeyboardEvent | InputEvent
Undo, from the keyboard, the Edit menu or a controller.
redoKeyboardEvent | InputEvent
Redo, from the keyboard, the Edit menu or a controller.
resetnone
A form reset.
restorenone
The browser restored state, like after going back, or a saved value was read back from storage.
imperativenone
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.

事件

回调先收到验证码,然后收到变更详情。

Prop所属部件收到
onValueChangeOTPInput(value, details):新验证码和原因
onValueCommitOTPInput(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.

运行于 React、Vue 和 web components。