导航

v2.1.0
表单

一次性验证码输入框

逐格输入一次性验证码,每格一个字符,例如短信中的六位数字。

本页内容

一次性验证码(OTP)输入框用于输入简短的验证码,每格输入一个字符,例如短信或身份验证器提供的六位数字。每格都是原生输入框,呈小凹槽状,材质与文本输入框相同。聚焦时,输入格升至面板表面,并显示墨色轮廓。在触屏上,可以通过页面上的数字键盘填写。

一次性验证码

<fieldset class="otp" aria-label="Verification code">  <input class="otp-slot" inputmode="numeric" pattern="[0-9]" maxlength="1" autocomplete="one-time-code" aria-label="Digit 1" value="4">  <input class="otp-slot" inputmode="numeric" pattern="[0-9]" maxlength="1" aria-label="Digit 2" value="2">  <input class="otp-slot" inputmode="numeric" pattern="[0-9]" maxlength="1" aria-label="Digit 3">  <span class="otp-separator" aria-hidden="true"></span>  <input class="otp-slot" inputmode="numeric" pattern="[0-9]" maxlength="1" aria-label="Digit 4">  <input class="otp-slot" inputmode="numeric" pattern="[0-9]" maxlength="1" aria-label="Digit 5">  <input class="otp-slot" inputmode="numeric" pattern="[0-9]" maxlength="1" aria-label="Digit 6"></fieldset><script type="module">  import { attach } from '@master/ui/behaviors'  attach()</script>
import { useEffect, useRef } from 'react'import { attach } from '@master/ui/behaviors'export function Example() {  const root = useRef<HTMLFieldSetElement>(null)  useEffect(() => attach(root.current!), [])  return (    <fieldset ref={root} className="otp" aria-label="Verification code">      <input className="otp-slot" inputMode="numeric" pattern="[0-9]" maxLength={1} autoComplete="one-time-code" aria-label="Digit 1" defaultValue="4" />      <input className="otp-slot" inputMode="numeric" pattern="[0-9]" maxLength={1} aria-label="Digit 2" defaultValue="2" />      <input className="otp-slot" inputMode="numeric" pattern="[0-9]" maxLength={1} aria-label="Digit 3" />      <span className="otp-separator" aria-hidden="true"></span>      <input className="otp-slot" inputMode="numeric" pattern="[0-9]" maxLength={1} aria-label="Digit 4" />      <input className="otp-slot" inputMode="numeric" pattern="[0-9]" maxLength={1} aria-label="Digit 5" />      <input className="otp-slot" inputMode="numeric" pattern="[0-9]" maxLength={1} aria-label="Digit 6" />    </fieldset>  )}
<script>  import { attach } from '@master/ui/behaviors'</script><fieldset class="otp" aria-label="Verification code" {@attach attach}>  <input class="otp-slot" inputmode="numeric" pattern="[0-9]" maxlength="1" autocomplete="one-time-code" aria-label="Digit 1" value="4">  <input class="otp-slot" inputmode="numeric" pattern="[0-9]" maxlength="1" aria-label="Digit 2" value="2">  <input class="otp-slot" inputmode="numeric" pattern="[0-9]" maxlength="1" aria-label="Digit 3">  <span class="otp-separator" aria-hidden="true"></span>  <input class="otp-slot" inputmode="numeric" pattern="[0-9]" maxlength="1" aria-label="Digit 4">  <input class="otp-slot" inputmode="numeric" pattern="[0-9]" maxlength="1" aria-label="Digit 5">  <input class="otp-slot" inputmode="numeric" pattern="[0-9]" maxlength="1" aria-label="Digit 6"></fieldset>
<script setup>import { onMounted, onUnmounted, ref } from 'vue'import { attach } from '@master/ui/behaviors'const root = ref(null)let detachonMounted(() => { detach = attach(root.value) })onUnmounted(() => detach?.())</script><template>  <fieldset ref="root" class="otp" aria-label="Verification code">    <input class="otp-slot" inputmode="numeric" pattern="[0-9]" maxlength="1" autocomplete="one-time-code" aria-label="Digit 1" value="4">    <input class="otp-slot" inputmode="numeric" pattern="[0-9]" maxlength="1" aria-label="Digit 2" value="2">    <input class="otp-slot" inputmode="numeric" pattern="[0-9]" maxlength="1" aria-label="Digit 3">    <span class="otp-separator" aria-hidden="true"></span>    <input class="otp-slot" inputmode="numeric" pattern="[0-9]" maxlength="1" aria-label="Digit 4">    <input class="otp-slot" inputmode="numeric" pattern="[0-9]" maxlength="1" aria-label="Digit 5">    <input class="otp-slot" inputmode="numeric" pattern="[0-9]" maxlength="1" aria-label="Digit 6">  </fieldset></template>
输入一位数字后,焦点移到下一格。按 Backspace 清空当前格,当前格为空时则退回上一格并清空该格。粘贴的验证码会分填到各格。

#交互行为

未加载脚本时,每格都是普通输入框。输入一个字符后,按 Tab 切换到下一格。otp 行为脚本让多个输入格用起来像一个输入框。脚本接收带有 otp 类的根元素,并返回一个用于解除绑定的函数。

app.js
import { otp } from '@master/ui/behaviors/otp.js'const root = document.querySelector('.otp')otp(root)root.addEventListener('change', (event) => {  if (event.detail) verify(event.detail.value)})
  • 输入。 输入一个字符后,焦点移到下一格。输入格会拒绝不允许的字符。聚焦时,格内已有的字符会被选中,继续输入即可替换。
  • 退格。 按 Backspace 清空当前格。如果当前格为空,焦点会移到上一格并清空该格。
  • 粘贴和自动填充。 粘贴或自动填充的验证码会分填到各格。完整验证码从第一格开始填,部分验证码从接收内容的那一格开始填。
  • 事件。 脚本写入某一格时,该格会像键入时一样触发 input。所有格都填满后,根元素会触发一个冒泡的 change 事件,验证码放在 detail.value 中。输入格自身的 change 事件也会冒泡经过根元素,但没有 detail,所以上面的监听器会检查该字段。
选项设置内容
pattern单个字符必须匹配的正则表达式。默认使用第一格的 pattern 属性,未设置该属性时只接受数字

第一格设置 autocomplete="one-time-code" 是为了支持自动填充。手机提供短信验证码时,会将整串验证码填入同一个输入框。maxlength="1" 会在脚本读取前将其截断为一个字符。绑定期间,行为脚本会移除各格的 maxlength,自行将每格限制为一个字符。解除绑定时会恢复该属性。没有脚本时,该属性会保留,自动填充只能填入验证码的第一个字符。因此,通过短信接收验证码时,建议使用单个输入框。

#无效状态

验证码错误时,将各格标记为 aria-invalid="true",并在输入组下方说明原因。

无效状态

<fieldset class="otp" aria-label="Verification code" aria-describedby="otp-error">  <input class="otp-slot" inputmode="numeric" maxlength="1" aria-label="Digit 1" aria-invalid="true" value="4">  <input class="otp-slot" inputmode="numeric" maxlength="1" aria-label="Digit 2" aria-invalid="true" value="2">  <input class="otp-slot" inputmode="numeric" maxlength="1" aria-label="Digit 3" aria-invalid="true" value="0">  <input class="otp-slot" inputmode="numeric" maxlength="1" aria-label="Digit 4" aria-invalid="true" value="9"></fieldset><p class="m(0) text-xs fg-danger" id="otp-error">That code has expired. Request a new one.</p>
<>  <fieldset className="otp" aria-label="Verification code" aria-describedby="otp-error">    <input className="otp-slot" inputMode="numeric" maxLength={1} aria-label="Digit 1" aria-invalid="true" defaultValue="4" />    <input className="otp-slot" inputMode="numeric" maxLength={1} aria-label="Digit 2" aria-invalid="true" defaultValue="2" />    <input className="otp-slot" inputMode="numeric" maxLength={1} aria-label="Digit 3" aria-invalid="true" defaultValue="0" />    <input className="otp-slot" inputMode="numeric" maxLength={1} aria-label="Digit 4" aria-invalid="true" defaultValue="9" />  </fieldset>  <p className="m(0) text-xs fg-danger" id="otp-error">That code has expired. Request a new one.</p></>
<fieldset class="otp" aria-label="Verification code" aria-describedby="otp-error">  <input class="otp-slot" inputmode="numeric" maxlength="1" aria-label="Digit 1" aria-invalid="true" value="4">  <input class="otp-slot" inputmode="numeric" maxlength="1" aria-label="Digit 2" aria-invalid="true" value="2">  <input class="otp-slot" inputmode="numeric" maxlength="1" aria-label="Digit 3" aria-invalid="true" value="0">  <input class="otp-slot" inputmode="numeric" maxlength="1" aria-label="Digit 4" aria-invalid="true" value="9"></fieldset><p class="m(0) text-xs fg-danger" id="otp-error">That code has expired. Request a new one.</p>
<template>  <fieldset class="otp" aria-label="Verification code" aria-describedby="otp-error">    <input class="otp-slot" inputmode="numeric" maxlength="1" aria-label="Digit 1" aria-invalid="true" value="4">    <input class="otp-slot" inputmode="numeric" maxlength="1" aria-label="Digit 2" aria-invalid="true" value="2">    <input class="otp-slot" inputmode="numeric" maxlength="1" aria-label="Digit 3" aria-invalid="true" value="0">    <input class="otp-slot" inputmode="numeric" maxlength="1" aria-label="Digit 4" aria-invalid="true" value="9">  </fieldset>  <p class="m(0) text-xs fg-danger" id="otp-error">That code has expired. Request a new one.</p></template>

#单个输入框即可

分格输入是一种可选的视觉惯例。为单个文本输入框设置 autocomplete="one-time-code"、inputmode="numeric" 和 maxlength="6",无需脚本即可接收同样的验证码,支持直接粘贴,也更便于使用屏幕阅读器。如果分格形式符合产品风格,可以采用分格输入。

#键盘操作

按键操作
A character填入当前输入格并将焦点移至下一格。当前格不接受的字符无法输入
Backspace清空当前输入格;若当前格为空,将焦点移到前一格并清空该格
Delete清空当前输入格
ArrowLeft, ArrowRight将焦点移到前一格或后一格。采用从右到左的布局时,左右方向键的作用互换。
Home, End将焦点移到第一格或最后一格。
Paste将粘贴的验证码逐位填入输入格。完整验证码从第一格填起,部分验证码从当前聚焦的输入格填起

#无障碍

  • 用带标签的 <fieldset> 将各格归为一组。每格没有可见标签,因此要为每格提供无障碍名称。
  • inputmode="numeric" 会调出数字键盘,不会将输入格变成数字类型的输入框。
  • 出错时保留已填内容,将各格标记为无效,让用户更正或重新粘贴。

#React、Svelte 和 Vue

otp 组件渲染各个输入格,绑定行为脚本,接收和传出验证码,并在填写完成时发出通知。使用 npx master-ui add otp 将它复制到项目中。React、Svelte 和 Vue介绍了这些组件的实现和用法。

ui/otp.tsx
'use client'import { useState, type ComponentProps } from 'react'import { otp } from '@master/ui/behaviors/otp.js'import { useBehavior } from './use-behavior'export interface OtpProps extends Omit<ComponentProps<'fieldset'>, 'defaultValue' | 'onChange' | 'ref'> {  /** How many characters the code has. */  length?: number  /** The characters typed so far. */  value?: string  defaultValue?: string  onValueChange?: (value: string) => void  /** Called with the code once every slot holds a character. */  onComplete?: (code: string) => void  /** What one character must match, as the `pattern` of each slot. A digit by default. */  pattern?: string  inputMode?: 'numeric' | 'text'  /** The name of a slot, which has no visible label. */  slotLabel?: (index: number) => string  invalid?: boolean}/** A one-time code. Name the group with `aria-label` or `aria-labelledby`; `disabled` disables every slot. *//** The behavior reads the slots and what a slot takes as it attaches, so it attaches again when either changes. */const slotted = (root: HTMLElement, _read?: { length: number, pattern: string }) => otp(root)export function Otp({ length = 6, value, defaultValue, onValueChange, onComplete, pattern = '[0-9]', inputMode = 'numeric', slotLabel = index => `Digit ${index + 1}`, invalid, className, ...root }: OtpProps) {  const ref = useBehavior(slotted, { length, pattern }, {    value,    defaultValue,    onValueChange,    // The root's own change is the behavior's: every slot is filled. A slot's change bubbles through it too.    on: { change: (event) => { if (event.target === event.currentTarget) onComplete?.((event as CustomEvent<{ value: string }>).detail.value) } },  })  const [first] = useState(value ?? defaultValue ?? '')  return (    <fieldset className={className ? `otp ${className}` : 'otp'} ref={ref} {...root}>      {Array.from({ length }, (_, index) => (        <input className="otp-slot" key={index} inputMode={inputMode} pattern={pattern} maxLength={1} autoComplete={index === 0 ? 'one-time-code' : 'off'} aria-label={slotLabel(index)} aria-invalid={invalid || undefined} defaultValue={first[index] ?? ''} />      ))}    </fieldset>  )}
ui/Otp.svelte
<script lang="ts" module>  import type { HTMLFieldsetAttributes } from 'svelte/elements'  export interface OtpProps extends Omit<HTMLFieldsetAttributes, 'children' | 'inputmode'> {    /** How many characters the code has. */    length?: number    /** The characters typed so far. Bind it, or leave it out. */    value?: string    onValueChange?: (value: string) => void    /** Called with the code once every slot holds a character. */    onComplete?: (code: string) => void    /** What one character must match, as the `pattern` of each slot. A digit by default. */    pattern?: string    inputmode?: 'numeric' | 'text'    /** The name of a slot, which has no visible label. */    slotLabel?: (index: number) => string    invalid?: boolean  }</script><script lang="ts">  import { untrack } from 'svelte'  import { otp } from '@master/ui/behaviors/otp.js'  import { behavior } from './behavior.svelte.js'  let { length = 6, value = $bindable(), onValueChange, onComplete, pattern = '[0-9]', inputmode = 'numeric', slotLabel = index => `Digit ${index + 1}`, invalid, class: className, ...root }: OtpProps = $props()  const first = untrack(() => value) ?? ''  // The behavior reads the slots and what a slot takes as it attaches, so it attaches again when either changes.  const slotted = (root: HTMLElement, _read?: { length: number, pattern: string }) => otp(root)  const attach = behavior(slotted, () => ({ length, pattern }), {    value: () => value,    change: (next) => { value = next; onValueChange?.(next) },    // The root's own change is the behavior's: every slot is filled. A slot's change bubbles through it too.    on: { change: (event) => { if (event.target === event.currentTarget) onComplete?.((event as CustomEvent<{ value: string }>).detail.value) } },  })</script><!--  @component  A one-time code. Name the group with `aria-label` or `aria-labelledby`; `disabled` disables every slot.--><fieldset class={['otp', className]} {@attach attach} {...root}>  {#each { length }, index}    <input class="otp-slot" {inputmode} {pattern} maxlength={1} autocomplete={index === 0 ? 'one-time-code' : 'off'} aria-label={slotLabel(index)} aria-invalid={invalid || undefined} value={first[index] ?? ''} />  {/each}</fieldset>
ui/Otp.vue
<script setup lang="ts">import { useTemplateRef } from 'vue'import { otp } from '@master/ui/behaviors/otp.js'import { useBehavior } from './use-behavior'defineOptions({ inheritAttrs: false })const { length = 6, pattern = '[0-9]', inputMode = 'numeric', slotLabel = (index: number) => `Digit ${index + 1}` } = defineProps<{  /** How many characters the code has. */  length?: number  /** What one character must match, as the `pattern` of each slot. A digit by default. */  pattern?: string  inputMode?: 'numeric' | 'text'  /** The name of a slot, which has no visible label. */  slotLabel?: (index: number) => string  invalid?: boolean}>()/** The characters typed so far: `v-model`. */const model = defineModel<string>()const emit = defineEmits<{  /** The code, once every slot holds a character. */  complete: [code: string]}>()/* A one-time code. Name the group with `aria-label` or `aria-labelledby`; `disabled` disables every slot. */const first = model.value ?? ''const root = useTemplateRef<HTMLFieldSetElement>('root')// The behavior reads the slots and what a slot takes as it attaches, so it attaches again when either changes.const slotted = (element: HTMLElement, _read?: { length: number, pattern: string }) => otp(element)useBehavior(root, slotted, () => ({ length, pattern }), model, {  // The root's own change is the behavior's: every slot is filled. A slot's change bubbles through it too.  change: (event) => { if (event.target === event.currentTarget) emit('complete', (event as CustomEvent<{ value: string }>).detail.value) },})</script><template>  <fieldset class="otp" ref="root" v-bind="$attrs">    <input v-for="index in length" :key="index" class="otp-slot" :inputmode="inputMode" :pattern="pattern" maxlength="1" :autocomplete="index === 1 ? 'one-time-code' : 'off'" :aria-label="slotLabel(index - 1)" :aria-invalid="invalid || undefined" :value.attr="first[index - 1]">  </fieldset></template>

#类名

类名说明
otp用于带标签的 fieldset,将输入格组成一组。
otp-slot一个绘制为小凹槽的 input,用于输入单个字符。没有可见标签,需提供名称,例如“第 1 位数字”
otp-separator输入格组之间的短横线,例如分成两组三格。用 aria-hidden="true" 隐藏。

#自定义属性

属性默认值说明
--otp-width2.5rem输入格宽度
--otp-height2.75rem输入格高度,本身已是便于触控的尺寸

#源码

@master/ui/components/otp.css
/* * OTP: a short code typed one character to a slot. * Each slot is a native input drawn as a small well, the same material as a text field, so a slot rises * to the sheet with an ink contour while it has focus. Moving on after a character and pasting a whole code * belong to a script; without one, every slot is still an input the keys can reach. * Geometry: a scale of its own, each slot 40px wide and 44px tall with a control's corner, 8px apart. */@layer components.ui {  .otp {    --otp-width: 2.5rem;    --otp-height: 2.75rem;    display: inline-flex;    align-items: center;    gap: .5rem;    min-width: 0;    margin: 0;    padding: 0;    border: 0;  }  .otp-slot {    width: var(--otp-width);    height: var(--otp-height);    margin: 0;    padding: 0;    border: 0;    border-radius: calc(var(--radius-control) * var(--corner-scale));    corner-shape: var(--corner-shape);    background: var(--color-surface-inset);    color: var(--color-text-strong);    box-shadow: var(--shadow-pressed);    font: var(--font-weight-control) 1.125rem/1 var(--font-family-sans);    font-feature-settings: inherit;    font-variant-numeric: tabular-nums;    text-align: center;    caret-color: var(--color-text-strong);    appearance: textfield;    transition-property: box-shadow, background-color;    transition-duration: var(--duration-quick);    transition-timing-function: var(--easing-glide);    /* A slot holds one character: a number field's steppers have nothing to step. */    &::-webkit-inner-spin-button, &::-webkit-outer-spin-button {      display: none;    }    &::placeholder {      color: var(--color-text-disabled);      opacity: 1;    }    @media (hover: hover) {      &:hover:not(:focus, :disabled, [readonly]) {        background: var(--color-surface-inset-hover);      }    }    /* Read only: the character is shown, not typed, so the slot rests flat and the caret is gone, as a field's does. */    &:where([readonly]:not(:disabled)) {      background: transparent;      box-shadow: var(--shadow-flat);      caret-color: transparent;    }    &:focus {      outline: none;      background: var(--color-surface-raised);      box-shadow: inset 0 0 0 .5px var(--color-line-mark), 0 0 0 .5px var(--color-line-mark), 0 0 0 3.5px var(--color-focus-halo);    }    /*     * Filled in by the browser, as the first slot is when a code is offered from a message: the engine paints its     * own background, so the well is laid over it as an inset shadow with the faint tint a text field takes.     */    &:autofill {      box-shadow: var(--shadow-pressed), inset 0 0 0 100vmax color-mix(in oklab, var(--color-info) 7%, var(--color-surface-inset));      &:focus {        box-shadow: inset 0 0 0 .5px var(--color-line-mark), 0 0 0 .5px var(--color-line-mark), 0 0 0 3.5px var(--color-focus-halo), inset 0 0 0 100vmax color-mix(in oklab, var(--color-info) 7%, var(--color-surface-raised));      }    }    /*     * After the browser's fill, as a text field's is, so a filled code that is wrong still shows that it is.     * :user-invalid reports the slot's own constraints (required, pattern) once the reader has tried, without script.     */    &:is([aria-invalid="true"], :user-invalid) {      box-shadow: var(--shadow-pressed), inset 0 0 0 .5px var(--color-danger), 0 0 0 .5px color-mix(in oklab, var(--color-danger) 45%, transparent);      &:focus {        box-shadow: inset 0 0 0 .5px var(--color-danger), 0 0 0 .5px var(--color-danger), 0 0 0 3.5px color-mix(in oklab, var(--color-danger) 15%, transparent);      }    }    &:disabled {      color: var(--color-text-disabled);      -webkit-text-fill-color: currentColor;      opacity: 1;      cursor: not-allowed;    }    @media (forced-colors: active) {      outline: 1px solid FieldText;      outline-offset: -1px;      &:focus {        outline: 2px solid Highlight;        outline-offset: -2px;      }      /* The danger edge is a shadow, which forced colors drop: the outline says it instead, as a field's does. */      &:is([aria-invalid="true"], :user-invalid) {        outline-color: Mark;      }      &:disabled {        outline-color: GrayText;      }    }  }  /* A short dash between groups of slots, such as three and three. */  .otp-separator {    flex: none;    width: .5rem;    height: 1.5px;    border-radius: 999px;    background: var(--color-line-mark);    @media (forced-colors: active) {      background: CanvasText;    }  }}