탐색

v2.1.0
폼

OTP

문자 메시지로 받은 6자리 숫자처럼 일회용 코드를 한 칸에 한 글자씩 입력하는 필드입니다.

이 페이지의 내용

OTP 필드에는 문자 메시지나 인증 앱에서 받은 여섯 자리 숫자처럼 짧은 코드를 한 칸에 한 글자씩 입력합니다. 각 칸은 텍스트 필드와 같은 질감의 작은 오목한 영역으로 표현한 기본 HTML 입력 요소입니다. 포커스가 있는 동안에는 입력 칸이 주변 표면과 같은 높이로 올라오고 짙은 윤곽선이 나타납니다. 터치 화면에서는 페이지에 표시된 키패드로 코드를 입력할 수 있습니다.

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문자 하나를 입력하는 요소를 작은 오목한 영역으로 표시합니다. 화면에 보이는 레이블이 없으므로 “첫 번째 숫자”와 같은 접근 가능한 이름을 지정해야 합니다.
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;    }  }}