網站導覽

v2.1.0
表單

OTP

逐格輸入一次性驗證碼,每格一個字元,例如簡訊中的六位數字。

本頁內容

OTP 欄位用來輸入簡短的驗證碼,例如簡訊或驗證器應用程式提供的六位數字,每格輸入一個字元。每格都是原生輸入欄位,外觀看起來像一個小凹槽,採用與文字欄位相同的樣式。取得焦點時,欄位會從凹槽抬升至與周圍齊平,並顯示深色輪廓線。在觸控螢幕上,也可以用頁面上的數字鍵盤填寫。

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>
輸入一個數字後,焦點會移到下一格。按退格鍵可往回移動,貼上的驗證碼則會分配到各格。

#行為

沒有腳本時,每格都是一般的輸入欄位。使用者輸入一個字元後,可以按 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;    }  }}