InputOtp
A row of single-character inputs for fixed-length codes such as SMS verification codes and one-time passwords. Entry advances focus automatically. Pasting a complete code and mobile SMS autofill are supported.
Import
import { HuiInputOtp } from '@nscode/handy-ui'
Basic Usage
Bind a string with v-model, such as '123456', or an empty string when no code is entered. Filling every cell emits finish with the complete value, which can be used to submit the code directly.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInputOtp, HuiMessage } from '@nscode/handy-ui'
const code = ref('')
const onFinish = (value: string) => {
HuiMessage.success(`Submit verification code ${value}`)
}
</script>
<template>
<HuiInputOtp v-model="code" @finish="onFinish" />
<p style="margin-top: 12px">Bound value: '{{ code }}'</p>
</template>
The bound value concatenates filled characters in order, excluding empty cells. For example, if the third cell is empty, the value is '12456'. Check whether the value length equals length, or use finish, to determine completion.
Digits Only
allow-input decides whether a character may enter the cell at index, starting at 0. Returning false ignores the character. This function receives one character, while the identically named HuiInput prop receives the whole prospective value. For numeric codes, also set inputmode="numeric" to show a numeric keyboard on mobile:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInputOtp } from '@nscode/handy-ui'
const code = ref('')
</script>
<template>
<HuiInputOtp v-model="code" :allow-input="(char) => /^\d$/.test(char)" inputmode="numeric" />
</template>
Both typing and pasting pass through allow-input. Whitespace, including spaces and newlines, is always ignored and needs no special handling. Use index for position-specific rules, such as letters in the first two cells and digits in the last four:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInputOtp } from '@nscode/handy-ui'
const code = ref('')
const allowInput = (char: string, index: number) =>
index < 2 ? /^[A-Za-z]$/.test(char) : /^\d$/.test(char)
</script>
<template>
<HuiInputOtp v-model="code" :allow-input="allowInput" placeholder="AB1234" />
</template>
Length
length is the number of cells and defaults to 6.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInputOtp, HuiSpace } from '@nscode/handy-ui'
const four = ref('')
const six = ref('')
const eight = ref('')
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<span class="row-label">length = 4</span>
<HuiInputOtp v-model="four" :length="4" />
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">6 (default)</span>
<HuiInputOtp v-model="six" />
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">length = 8</span>
<HuiInputOtp v-model="eight" :length="8" />
</HuiSpace>
</HuiSpace>
</template>
<style scoped>
.row-label {
display: inline-block;
width: 88px;
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
</style>
Mask and Placeholder
mask displays entered characters as dots, making each cell a password input. placeholder specifies empty-cell placeholders: one character repeats in every cell; with multiple characters, cell n displays character n.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInputOtp, HuiSpace } from '@nscode/handy-ui'
const pin = ref('123')
const code = ref('')
const date = ref('')
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<span class="row-label">mask</span>
<HuiInputOtp v-model="pin" mask />
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">One character</span>
<HuiInputOtp v-model="code" placeholder="○" />
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">Multiple characters</span>
<HuiInputOtp v-model="date" placeholder="YYMMDD" />
</HuiSpace>
</HuiSpace>
</template>
<style scoped>
.row-label {
display: inline-block;
width: 72px;
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
</style>
Sizes
size accepts large, default or small. Each cell is square, with a side length matching the height of an input or button of the same size:
| Size | Cell Side | Font Size | Radius | Cell Gap |
|---|---|---|---|---|
| large | 40px | 16px | 8px | 12px |
| default | 32px | 14px | 6px | 8px |
| small | 24px | 12px | 4px | 6px |
When omitted, size follows HuiFormItem, then HuiForm, then HuiConfigProvider, and finally default. Each row ends with a matching button for height comparison:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiInputOtp, HuiSpace } from '@nscode/handy-ui'
const code = ref('1234')
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<span class="row-label">large</span>
<HuiInputOtp v-model="code" size="large" />
<HuiButton size="large" type="primary">Verify</HuiButton>
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">default</span>
<HuiInputOtp v-model="code" />
<HuiButton type="primary">Verify</HuiButton>
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">small</span>
<HuiInputOtp v-model="code" size="small" />
<HuiButton size="small" type="primary">Verify</HuiButton>
</HuiSpace>
</HuiSpace>
</template>
<style scoped>
.row-label {
display: inline-block;
width: 56px;
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
</style>
Gap and Full Width
gap changes the distance between cells. Numbers use pixels; strings such as '1rem' are also accepted. block fills the parent width, distributing that width equally among cells without changing their height.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInputOtp, HuiSpace } from '@nscode/handy-ui'
const code = ref('')
</script>
<template>
<HuiSpace direction="vertical" fill>
<HuiInputOtp v-model="code" :gap="4" />
<HuiInputOtp v-model="code" :gap="16" />
<HuiInputOtp v-model="code" gap="2rem" />
<HuiInputOtp v-model="code" block />
</HuiSpace>
</template>
Disabled and Read Only
disabled disables every cell and follows the enclosing HuiForm's disabled state. With readonly, cells can receive focus and arrow-key navigation, but typing, deleting and pasting are disabled.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInputOtp, HuiSpace } from '@nscode/handy-ui'
const code = ref('123456')
const empty = ref('')
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSpace wrap>
<span class="row-label">disabled</span>
<HuiInputOtp v-model="code" disabled />
<HuiInputOtp v-model="empty" :length="4" placeholder="-" disabled />
</HuiSpace>
<HuiSpace wrap>
<span class="row-label">readonly</span>
<HuiInputOtp v-model="code" readonly />
<HuiInputOtp v-model="empty" :length="4" placeholder="-" readonly />
</HuiSpace>
</HuiSpace>
</template>
<style scoped>
.row-label {
display: inline-block;
width: 64px;
color: var(--hui-text-color-secondary);
font-size: var(--hui-font-size-sm);
}
</style>
Keyboard Type
inputmode selects the mobile keyboard, matching the native input attribute. Values are text (default), numeric, decimal, tel, email, url, search and none (no keyboard). This has no visible effect on desktop; open this page on a phone, select a mode and focus a cell:
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInputOtp, HuiSegmented, HuiSpace } from '@nscode/handy-ui'
import type { InputOtpInputMode } from '@nscode/handy-ui'
const modes: InputOtpInputMode[] = [
'text',
'numeric',
'decimal',
'tel',
'email',
'url',
'search',
'none'
]
const mode = ref<InputOtpInputMode>('numeric')
const code = ref('')
</script>
<template>
<HuiSpace direction="vertical" align="start">
<HuiSegmented v-model="mode" :options="modes" size="small" />
<HuiInputOtp v-model="code" :inputmode="mode" />
</HuiSpace>
</template>
Events
Typing, deleting or pasting that changes the value emits change together with update:modelValue. Filling every cell then emits finish. focus and blur fire only when focus enters or leaves the entire component, not when moving between cells. Their second argument is the zero-based cell index.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInputOtp } from '@nscode/handy-ui'
const code = ref('')
const logs = ref<string[]>([])
const log = (text: string) => {
logs.value = [text, ...logs.value].slice(0, 6)
}
const onChange = (value: string) => log(`change:'${value}'`)
const onFinish = (value: string) => log(`finish:'${value}'`)
const onFocus = (_event: FocusEvent, index: number) => log(`focus: cell ${index + 1}`)
const onBlur = (_event: FocusEvent, index: number) => log(`blur: cell ${index + 1}`)
</script>
<template>
<HuiInputOtp
v-model="code"
:length="4"
@change="onChange"
@finish="onFinish"
@focus="onFocus"
@blur="onBlur"
/>
<p style="margin-top: 12px">Recent events (newest first): {{ logs.join(', ') || 'None yet' }}</p>
</template>
Validation State
There is no separate status prop. The enclosing HuiFormItem controls error appearance. When validation fails or the form item receives error, every cell gets a danger-colored border and an error message appears below.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiForm, HuiFormItem, HuiInputOtp, HuiSwitch } from '@nscode/handy-ui'
const showError = ref(true)
const code = ref('1234')
</script>
<template>
<HuiSwitch v-model="showError" active-text="Show error" />
<HuiForm label-width="80px" style="margin-top: 16px" @submit.prevent>
<HuiFormItem
label="Verification code"
:error="showError ? 'Incorrect verification code. Enter it again' : ''"
>
<HuiInputOtp v-model="code" />
</HuiFormItem>
</HuiForm>
</template>
Within a Form
Inside HuiFormItem, InputOtp behaves like other form controls:
- The label's
forpoints to the first cell, so clicking the label focuses it. The group is associated with the label througharia-labelledby. - Value changes trigger
changevalidation. Focus leaving the entire component, rather than moving between cells, triggersblurvalidation. SetvalidateEventtofalseto disable both triggers. - Validation errors turn every cell border red.
<script setup lang="ts">
import { reactive } from 'vue'
import { HuiForm, HuiFormItem, HuiInputOtp } from '@nscode/handy-ui'
const form = reactive({ code: '' })
const rules = {
code: [
{ required: true, message: 'Enter a verification code', trigger: 'blur' },
{ min: 6, message: 'The verification code has 6 characters', trigger: 'blur' }
]
}
</script>
<template>
<HuiForm :model="form" :rules="rules">
<HuiFormItem label="Verification code" prop="code">
<HuiInputOtp v-model="form.code" inputmode="numeric" />
</HuiFormItem>
</HuiForm>
</template>
Keyboard Interaction
| Key | Action |
|---|---|
| Type a character | Fills the current cell and advances focus. After the last cell is filled, focus stays there |
| Backspace key | Deletes a character in the current cell without moving focus. If already empty, deletes the previous cell and moves there |
| Delete | Clears the current cell without moving focus |
| ← → | Moves to the previous or next cell, stopping at either end |
| Home / End | Moves to the first or last cell |
| Tab | Visits each cell in sequence |
| Paste a code | Fills cells starting at the current one, skips disallowed characters and discards characters beyond the available cells |
Focusing a cell, including through a click or arrow key, selects its character so subsequent typing replaces it.
SMS Code Autofill
The first cell has autocomplete="one-time-code". iOS and Android keyboards can offer a received SMS code; selecting it fills the first cell with the full code, which is distributed across cells through allow-input, just like pasting. Remaining cells use autocomplete="off".
Internal State and Controlled Updates
Without modelValue, or with only an update listener, input is stored internally starting from an empty string. Providing the prop makes it controlled, including undefined, which displays as empty. If the parent rejects an update, native inputs restore the accepted content. After the parent accepts deletion, middle gaps remain in place; parent redraws do not compact them. Dynamically removing the prop restores previous internal positions. Switching modes warns and cancels an old IME session. Reducing length discards characters beyond the new length; increasing it later does not restore them. change and finish report the current input request, while controlled display still depends on the parent's accepted value.
<script setup lang="ts">
import { ref } from 'vue'
import { HuiInputOtp, HuiButton, HuiSpace } from '@nscode/handy-ui'
const q1Redraw = ref(0)
const q1Last = ref('No request yet')
const q1Model = ref('')
</script>
<template>
<HuiSpace class="input-otp-q1-demo" direction="vertical" fill>
<HuiButton class="q1-redraw" @click="q1Redraw++">Parent redraw {{ q1Redraw }}</HuiButton>
<div class="q1-local">
<p>Prop omitted; internal state</p>
<HuiInputOtp :length="4" />
</div>
<div class="q1-listener">
<p>Update listener only; still internal state</p>
<HuiInputOtp :length="4" @update:model-value="q1Last = $event" />
</div>
<div class="q1-empty">
<p>Explicit undefined; stays empty</p>
<HuiInputOtp :length="4" :model-value="undefined" />
</div>
<div class="q1-fixed">
<p>Fixed controlled value; parent rejects updates</p>
<HuiInputOtp :length="4" model-value="12" />
</div>
<div class="q1-bound">
<p>Two-way binding</p>
<HuiInputOtp :length="4" v-model="q1Model" />
</div>
<p class="q1-notification">Bound value: {{ q1Model }}; latest request: {{ q1Last }}</p>
</HuiSpace>
</template>
Props
| Prop | Type | Default | Description |
|---|---|---|---|
| modelValue | string | undefined | Bound value for v-model, concatenating filled characters and excluding empty cells. Controlled when provided, including undefined; otherwise stored internally |
| length | number | 6 | Number of cells. Fractions are rounded down; values below 1, NaN and Infinity use 6 and produce a console warning |
| mask | boolean | false | Whether to display entered characters as dots |
| placeholder | string | '' | Empty-cell placeholder. One character repeats; multiple characters map to their corresponding cells |
| allowInput | (char: string, index: number) => boolean | - | Whether a character may enter the zero-based cell index. False ignores it. Used for both typing and pasting |
| gap | number | string | - | Cell gap. Numbers use pixels; defaults to 12 / 8 / 6px by size |
| block | boolean | false | Whether to fill the parent width with equally sized cells |
| disabled | boolean | false | Whether the component is disabled |
| readonly | boolean | false | Allows focus and navigation but prevents typing, deleting and pasting |
| size | 'large' | 'default' | 'small' | - | Follows FormItem, Form and ConfigProvider, then default |
| inputmode | InputOtpInputMode | 'text' | Mobile keyboard type. Use numeric for digit-only codes |
| validateEvent | boolean | true | Whether value changes and focus leaving the component trigger form-item validation |
Events
| Event | Callback Arguments | Description |
|---|---|---|
| update:modelValue | (value: string) | Emitted for value changes from typing, deleting or pasting; used by v-model |
| change | (value: string) | Emitted for user-driven value changes together with update:modelValue. External changes do not emit it |
| finish | (value: string) | Emitted after a user action fills every cell, with the complete value. Not repeated when the value is unchanged |
| focus | (event: FocusEvent, index: number) | Focus enters the component at cell index. Moving between cells does not emit it |
| blur | (event: FocusEvent, index: number) | Focus leaves the entire component. Index is the previously focused cell. Moving between cells does not emit it |
Slots
None.
Methods
Call through an HuiInputOtp ref.
| Method | Arguments | Return Value | Description |
|---|---|---|---|
| focus | (index?: number) | void | Focuses the zero-based cell index, clamped to either end. Without an index, focuses the first empty cell or the last cell when all are filled |
| blur | - | void | Blurs the currently focused cell |
For example, after resending a code, clear the input and focus the first cell. The buttons below demonstrate focus(), focus(2) and blur():
<script setup lang="ts">
import { ref } from 'vue'
import { HuiButton, HuiInputOtp, HuiSpace } from '@nscode/handy-ui'
const code = ref('12')
const otpRef = ref<InstanceType<typeof HuiInputOtp>>()
const resend = () => {
code.value = ''
otpRef.value?.focus(0)
}
</script>
<template>
<HuiInputOtp ref="otpRef" v-model="code" />
<div style="margin-top: 12px">
<HuiSpace wrap>
<HuiButton type="primary" @click="resend">Resend (clear and focus the first cell)</HuiButton>
<HuiButton @click="otpRef?.focus()">Focus the first empty cell</HuiButton>
<HuiButton @click="otpRef?.focus(2)">Focus cell 3</HuiButton>
<HuiButton @click="otpRef?.blur()">Blur</HuiButton>
</HuiSpace>
</div>
</template>
Types
import type {
InputOtpProps,
InputOtpEmits,
InputOtpSize,
InputOtpInputMode
} from '@nscode/handy-ui'
type InputOtpSize = 'large' | 'default' | 'small'
type InputOtpInputMode =
| 'text'
| 'numeric'
| 'decimal'
| 'tel'
| 'email'
| 'url'
| 'search'
| 'none'