ナビゲーション

v2.1.0
フォーム

OTP

ワンタイムコードを 1 枠に 1 文字ずつ入力するフィールド。SMS で届く 6 桁の数字などに。

このページの内容

OTP フィールドには、SMS で届く、または認証アプリに表示される 6 桁の数字など、短いコードを 1 枠に 1 文字ずつ入力します。各枠はネイティブの入力要素です。テキストフィールドと同じ質感の小さなくぼみとして表示され、フォーカス時は面と同じ高さになり、文字色の輪郭が付きます。タッチ画面では、ページ上のキーパッドからも入力できます。

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 キーで前の枠に戻れます。コードを貼り付けると、各枠に 1 文字ずつ入ります。

#ビヘイビア

スクリプトがなければ、各枠は通常の入力要素として機能します。1 文字入力し、Tab キーで次の枠に移動します。otp ビヘイビアを使うと、複数の枠を 1 つのフィールドとして操作できます。このビヘイビアは 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)})
  • 文字入力 1 文字入力すると、フォーカスが次の枠に移ります。枠で許可されていない文字は入力できません。枠にフォーカスが移ると入力済みの文字が選択され、そのまま入力すれば置き換えられます。
  • 削除と移動 Backspace キーを押すと、現在の枠の文字が消えます。枠が空の場合は、前の枠に移動してその文字を消します。
  • 貼り付けと自動入力 貼り付けや自動入力で受け取ったコードは、各枠に 1 文字ずつ入ります。コード全体を受け取った場合は先頭の枠から、一部だけを受け取った場合は入力先の枠から入ります。
  • イベント スクリプトが値を書き込んだ枠では、手入力時と同様に input が発行されます。すべての枠が埋まると、ルート要素は detail.value にコードを格納した、バブリングする change を発行します。各枠自身の change もルート要素までバブリングしますが、detail を持たないため、上のリスナーではその有無を確認しています。
オプション設定内容
pattern入力する 1 文字が一致すべき正規表現。既定では先頭の枠の pattern 属性を使い、属性がなければ数字を許可します。

先頭の枠に autocomplete="one-time-code" を付けるのは、自動入力に対応するためです。スマートフォンで SMS のコードを自動入力すると、1 つのフィールドにコード全体が入ります。maxlength="1" があると、スクリプトが受け取る前にコードが 1 文字に切り詰められます。ビヘイビアの適用中は各枠から maxlength を外し、ビヘイビア自体が各枠を 1 文字に制限します。適用を解除すると属性は元に戻ります。スクリプトがない場合は属性が残り、自動入力で先頭の 1 文字しか入らないため、SMS でコードを届ける場合は単一のフィールドが適しています。

#エラー状態

コードが正しくない場合は、各枠に 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-slot1 文字を入力する input に適用し、小さなくぼみのように表示します。ラベルは画面に表示されないため、「Digit 1」などのアクセシブルな名前を付けます。
otp-separator入力枠を 3 枠ずつに分ける場合などに、グループの間に置く短いダッシュです。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;    }  }}