OTP Input
输入一次性验证码,支持粘贴、自动填充和原生表单校验。
用 OTP Input 输入短信或邮件发来的短验证码,比如登录验证码或校验码。每个字符都有自己的槽位,粘贴或自动填充的验证码会一次填满所有槽位。
import "@ui-sdk/web/otp-input"
import "@ui-sdk/web/field"
import { createElement, Minus } from "lucide"
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-field>
<ui-field-label>Verification code</ui-field-label>
<ui-otp-input max-length="6">
<ui-otp-input-group>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
</ui-otp-input-group>
<ui-otp-input-separator>${createElement(Minus, { "aria-hidden": "true" }).outerHTML}</ui-otp-input-separator>
<ui-otp-input-group>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
</ui-otp-input-group>
</ui-otp-input>
</ui-field>
`
}
export { mount }安装
npm install @ui-sdk/web @ui-sdk/core导入组件会定义它的元素。如果你用到字段,也导入它。在服务器上,导入不会做任何事。
import "@ui-sdk/web/otp-input"
import "@ui-sdk/web/field"组合
用下面的组合构建 ui-otp-input:
ui-otp-input
└── ui-otp-input-group
├── ui-otp-input-slot
└── ui-otp-input-slotui-otp-input 创建原生输入框并保存验证码。ui-otp-input-group 排布一连串槽位。每个 ui-otp-input-slot 显示它在输入框槽位中所处位置的字符;如果你设置了从 0 开始的 index,就显示该位置的字符。当验证码分段更易读时,在组之间加上 ui-otp-input-separator,比如上面示例里的短横线。
组和分隔符只改变同一个值的呈现方式。它们不会创建额外的字段或 Tab 停靠点:这些槽位显示的是单个原生输入框的值,由它处理选择、粘贴、撤销、表单提交和自动填充。它使用 autocomplete="one-time-code",让支持的浏览器和密码管理器可以提供已保存或刚收到的验证码。
用法
导入部件并把它们组合起来:
<script type="module">
import "@ui-sdk/web/otp-input"
</script>
<ui-otp-input max-length="4" aria-label="Verification code">
<ui-otp-input-group>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
</ui-otp-input-group>
</ui-otp-input>四位数字
把 max-length 设为验证码的长度,并渲染同样多的槽位。默认长度是六位。
import "@ui-sdk/web/otp-input"
import "@ui-sdk/web/field"
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-field>
<ui-field-label>PIN</ui-field-label>
<ui-otp-input max-length="4" text-align="center">
<ui-otp-input-group>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
</ui-otp-input-group>
</ui-otp-input>
</ui-field>
`
}
export { mount }字母与数字
把 pattern 设为 digits、letters 或 alphanumeric。默认是 digits。模式会过滤字符,并在触摸设备上选择合适的键盘。
import "@ui-sdk/web/otp-input"
import "@ui-sdk/web/field"
import { createElement, Minus } from "lucide"
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-field>
<ui-field-label>Recovery code</ui-field-label>
<ui-otp-input max-length="8" pattern="alphanumeric">
<ui-otp-input-group>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
</ui-otp-input-group>
<ui-otp-input-separator>${createElement(Minus, { "aria-hidden": "true" }).outerHTML}</ui-otp-input-separator>
<ui-otp-input-group>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
</ui-otp-input-group>
</ui-otp-input>
</ui-field>
`
}
export { mount }自定义模式
传入正则表达式的源码,比如 pattern="[0-9A-Fa-f]",来接受十六进制字符。用 input-mode 单独选择键盘。示例以大写显示字母,但不改变存储的大小写。
import "@ui-sdk/web/otp-input"
import "@ui-sdk/web/field"
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-field>
<ui-field-label>Device code</ui-field-label>
<ui-otp-input max-length="6" pattern="[0-9A-Fa-f]" input-mode="text">
<ui-otp-input-group>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
</ui-otp-input-group>
</ui-otp-input>
</ui-field>
`
}
export { mount }校验
在 Field 里,当你的代码拒绝这个值时,在 ui-field 上设置 invalid,比如服务器没有接受的验证码。字段会用 aria-invalid 标记输入框,并关联它的 ui-field-error。在字段之外,需要你自己传入 aria-invalid 和 aria-describedby。
import "@ui-sdk/web/otp-input"
import "@ui-sdk/web/field"
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-field invalid>
<ui-field-label>Verification code</ui-field-label>
<ui-otp-input default-value="482913">
<ui-otp-input-group>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
</ui-otp-input-group>
</ui-otp-input>
<ui-field-error>That code has expired. Request a new one.</ui-field-error>
</ui-field>
`
const field = root.querySelector("ui-field")!
root.querySelector("ui-otp-input")!.addEventListener("valuechange", () => {
field.invalid = false
})
}
export { mount }受控
监听 valuechange 读取变更,并设置元素的 value property 来更新它。在监听器里调用 event.preventDefault() 来拒绝一次变更。传入的值会像输入的值一样,按模式过滤,并限制在 max-length 以内。
import "@ui-sdk/web/otp-input"
import "@ui-sdk/web/field"
import { log } from "./log"
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-field>
<ui-field-label>One-time password</ui-field-label>
<ui-otp-input>
<ui-otp-input-group>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
</ui-otp-input-group>
</ui-otp-input>
</ui-field>
`
root
.querySelector("ui-otp-input")!
.addEventListener("valuechange", (event) => {
const { value, reason } = event.detail
log(root, `${value || "Empty"} (${reason})`)
})
}
export { mount }受控状态的通用约定见状态与事件。原因区分输入、粘贴、撤销和控制器动作。
填满时
valuecommit 会在一次变更填满所有槽位时触发,包括输入、粘贴、自动填充和控制器写入。修改已经填满的验证码会再次触发它。表单重置和页面恢复不会。
import "@ui-sdk/web/otp-input"
import "@ui-sdk/web/field"
import { log } from "./log"
function mount(root: HTMLElement) {
root.innerHTML = `
<ui-field>
<ui-field-label>Verification code</ui-field-label>
<ui-otp-input>
<ui-otp-input-group>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
</ui-otp-input-group>
</ui-otp-input>
</ui-field>
`
root
.querySelector("ui-otp-input")!
.addEventListener("valuecommit", (event) => {
const { value, reason } = event.detail
log(root, `Checking ${value} (${reason})`)
})
}
export { mount }表单
设置 name,让验证码进入 FormData。required 会阻止空验证码,不完整的验证码无法通过长度校验。重置会恢复默认值。用 form 把表单外的控件关联到表单的 ID。
import "@ui-sdk/web/otp-input"
import "@ui-sdk/web/field"
import { log } from "./log"
function mount(root: HTMLElement) {
root.innerHTML = `
<div data-slot="stack">
<form id="verify-sign-in">
<ui-field>
<ui-field-label>Verification code</ui-field-label>
<ui-otp-input name="code" required>
<ui-otp-input-group>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
</ui-otp-input-group>
</ui-otp-input>
<ui-field-description>Enter the six-digit code we sent to hollis@example.com.</ui-field-description>
<ui-field-error></ui-field-error>
</ui-field>
</form>
<ui-field>
<ui-field-label>Recovery code (optional)</ui-field-label>
<ui-otp-input name="recovery" form="verify-sign-in" max-length="8" pattern="alphanumeric">
<ui-otp-input-group>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
<ui-otp-input-slot></ui-otp-input-slot>
</ui-otp-input-group>
</ui-otp-input>
<ui-field-error></ui-field-error>
</ui-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>
`
const form = root.querySelector("form")!
form.addEventListener("submit", (event) => {
event.preventDefault()
const data = [...new FormData(form)].map(
([name, value]) => `${name}=${value}`
)
log(root, `Submitted ${data.join(", ")}`)
})
}
export { mount }输入的不完整验证码会报告 tooShort。不完整的默认值和控制器写入会通过原生输入框的模式检查,因为浏览器不会对这些值应用 minlength 校验。
禁用与只读
禁用的输入框无法聚焦、更改或提交。read-only 阻止更改,同时让输入框保持可聚焦,并保留在表单数据里。
<ui-otp-input disabled default-value="123456" aria-label="Disabled code">
...
</ui-otp-input>
<ui-otp-input read-only default-value="654321" aria-label="Read-only code">
...
</ui-otp-input>控制器
用元素的 api 从另一个控件读取、填充、清空或聚焦输入框。写入使用 imperative 原因,并像输入一样经过相同的过滤和 valuechange 事件。
<button type="button" data-action="fill">Fill</button>
<button type="button" data-action="clear">Clear</button>
<button type="button" data-action="read">Read</button>
<button type="button" data-action="focus">Focus</button>
<ui-otp-input aria-label="Verification code"> ... </ui-otp-input>const code = document.querySelector("ui-otp-input")!.api
document
.querySelector('[data-action="fill"]')!
.addEventListener("click", () => code.setValue("123456"))
document
.querySelector('[data-action="clear"]')!
.addEventListener("click", () => code.clear())
document
.querySelector('[data-action="read"]')!
.addEventListener("click", () => console.log(code.getValue()))
document
.querySelector('[data-action="focus"]')!
.addEventListener("click", () => code.focus())控制器介绍了元素的 api。
自定义渲染
元素没有渲染函数。每个槽位显示自己的字符,并用 data-active 和 data-fake-caret 标记 active 和 hasFakeCaret。从 value property 或 valuechange 事件读取完整验证码。关于部件绑定哪些元素,见部件与组合。
样式
用 data-active 和 data-fake-caret 绘制活动的槽位和光标。示例包含光标动画,并在用户偏好减少动态效果时禁用动画。让每个槽位保持 position: relative,这样它的光标会留在槽位内部。
每个部件都有一个 data-slot,比如 otp-input-slot,它的状态属性列在数据属性下。
数据属性
<ui-otp-input>
[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. |
<ui-otp-input-group>
[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. |
<ui-otp-input-slot>
[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. |
<ui-otp-input-separator>
[data-slot="otp-input-separator"]
| 属性 | 含义 |
|---|---|
data-disabled | Present when disabled, by its own prop or a <fieldset>. |
API 参考
Props 是以 kebab 命名的属性,比如 max-length、default-value 和 read-only。pattern 是预设名称或正则表达式的源码。controller 是一个 property。回调是 DOM 事件。
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.
valuechange event- 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. valuecommit event- 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>.
原因
event.detail.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
apicall.
控制器
元素的 api property 有相同的方法。value property 读取并设置验证码。
setValue() 和 clear() 接受可选的 { reason, event },并像输入一样触发 valuechange。
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.
事件
事件在各自的元素上触发,不冒泡,验证码在 event.detail.value 里,旁边还有 reason 和 event。在 valuechange 上调用 preventDefault() 会取消这次变更。
| 成员 | 所属元素 | 说明 |
|---|---|---|
value property, attribute | ui-otp-input | 验证码 |
api property | ui-otp-input | 控制器 |
valuechange event | ui-otp-input | detail: { value, reason, event },每次变更时 |
valuecommit event | ui-otp-input | detail: { value, reason, event },变更填满所有槽位时 |
无障碍
用 ui-field-label、原生 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。