Command palette

@yasinsensoy/web

Web · Components

OtpInput

One-time code (OTP), verification code and PIN input.

7 exports

Live example

Preview

You can resend in 0:15

Try typing, pasting the SMS text and clicking the boxes.

Code

import { OtpField } from "@yasinsensoy/web";

<OtpField label="Verification code" name="code" groups={3} required
  onResend={resendCode}
  onComplete={verify} />

Events

  1. Events appear here when you interact with the preview.

Verification on the server: the boxes shake on a wrong code (the right code is 123456)

You can resend in 0:30

PIN: 4 digits, hidden, underline

License key: letters+digits, uppercase, groups of 4, joined boxes

X
X
X
X
X
X
X
X
X
X
X
X

Custom set (no 0/O and 1/I) and a dot as the separator

Controlled usage

4
2

Value: "42"

Import

import { OtpInput, extractOtp } from "@yasinsensoy/web";

OtpInput

componentClient component

One-time code (OTP), verification code and PIN input. The code appears in boxes but there is a single <input> behind them; this way SMS autofill, pasting, screen readers and forms work without issues.

  • Characters: With charset, only digits, letters, letters+digits, hex or your own set. Non-matching keys are ignored; casing upper- or lower-cases letters.
  • Pasting: Even if the whole SMS is pasted, the code inside is found ("Your code: 482-913" → 482913). See extractOtp.
  • Autofill: With autoComplete="one-time-code" the iOS/Android keyboard suggests the code from the SMS; webOtp reads the code from the SMS itself on Android Chrome.
  • Editing: Clicking a box selects that character and what you type replaces it. ←/→ move between boxes, Backspace deletes and goes back.
  • Mobile: The right keyboard opens (a digit keyboard for digits). A long press shows the browser's "Paste" menu.
  • Form: With name, the code itself enters FormData. If the code is incomplete browser validation gives patternMismatch, and an empty required one valueMissing. The boxes shake briefly on error.
  • When complete: onComplete is called; with autoSubmit the form is submitted automatically.

For use with a label, description and error message, see OtpField.

OtpInput({ length, charset, casing, value, defaultValue, onValueChange, onComplete, autoSubmit, groups, separator, mask, placeholder, size, variant: variantProp, effect, webOtp, onResend, resendDelay, className, style, ref, disabled, readOnly, inputMode, autoComplete, onKeyDown, onPaste, onFocus, onBlur, onClick, onPointerDown, ...props }: OtpInputProps): JSX.Element

Examples

<OtpInput name="code" aria-label="Verification code" autoFocus autoSubmit />

<OtpInput length={8} charset="alphanumeric" casing="upper" groups={4} aria-label="License code" />

<OtpInput length={4} mask aria-label="PIN" onComplete={(pin) => unlock(pin)} />

<OtpInput name="code" groups={3} webOtp onResend={() => sendCode()} resendDelay={30} />

extractOtp

function

Extracts the code from pasted or autofilled text.

  1. If the whole text, with spaces and dashes removed, is valid and not longer than the code, it is taken ("123 456", "AB-12-CD").
  2. Otherwise it looks for the first valid run of exactly length characters, so the code is found even when the whole SMS is pasted ("Your verification code: 482913. Valid for 5 min." → "482913").
  3. Failing that, it collects the valid characters in order.

The result is at most length characters; an empty string when no character is valid.

extractOtp(text: string, { length, charset, casing }: ExtractOtpOptions): string

Examples

extractOtp("Your code: 482-913", { length: 6 }); // "482913"
extractOtp("code ab12cd", { length: 6, charset: "alphanumeric", casing: "upper" }); // "AB12CD"

Characters that can be typed in a one-time code field (OtpInput).

  • "numeric": digits only (0-9). Opens the numeric keyboard on mobile.
  • "alphabetic": letters of the English alphabet only (A-Z).
  • "alphanumeric": letters and digits (A-Z, 0-9).
  • "hex": hexadecimal (0-9, A-F).
  • "any": any character except whitespace.
  • Any other string: only the characters in that string (e.g. a set without 0/O and 1/I to avoid confusion: "ABCDEFGHJKLMNPQRSTUVWXYZ23456789"). Can also be passed from server components.
  • RegExp: expression tested against each character (e.g. /[0-9A-F]/i). Can't be passed from a server component to the client; only in "use client" files.
type OtpCharset = "numeric" | "alphabetic" | "alphanumeric" | "hex" | "any" | RegExp | (string & {})

Case letters are converted to.

type OtpCasing = "upper" | "lower"

extractOtp options.

NameTypeDefaultDescription
lengthnumberCode length.
charset?OtpCharset"numeric"Charset.
casing?OtpCasingCase letters are converted to.

Look of the OtpInput boxes.

type OtpInputVariant = "outline" | "joined" | "underline"

OtpInputProps

interface

Props of the OtpInput component.

Extends: Omit<ComponentProps<"input">, "value" | "defaultValue" | "onChange" | "type" | "size" | "maxLength" | "minLength" | "pattern" | "placeholder" | "children">

NameTypeDefaultDescription
length?number6Number of characters in the code.
charset?OtpCharset"numeric"Characters that can be typed: "numeric", "alphabetic", "alphanumeric", "hex", "any", a string of allowed characters ("ABCDEF0123456789") or a RegExp. Non-matching keys are ignored. See OtpCharset.
casing?OtpCasingConverts letters to upper ("upper") or lower ("lower") case while typing. If omitted, they stay as is. With upper case the mobile keyboard also opens in upper case.
value?stringCode when controlled.
defaultValue?stringInitial code when uncontrolled.
onValueChange?(value: string) => voidCalled whenever the code changes.
onComplete?(value: string) => voidCalled once when all boxes are filled (by typing, pasting or autofill from SMS). For verifying the code on the server.
autoSubmit?booleanfalseSubmit the form it belongs to automatically when the code is complete?
groups?number | readonly number[]Groups the boxes and puts OtpInputProps.separator between them. With a number each group has that many boxes (3 → 123-456); with an array, the group sizes ([3, 2, 3]).
separator?ReactNodea short dashSeparator between groups.
mask?booleanfalseHides characters with dots (•) (like a PIN). The last typed character is visible briefly, like on phone keyboards.
placeholder?stringFaint character shown in empty boxes. A single character is shown in every box ("○"); a longer text is distributed across the boxes in order ("123456").
size?Size"md"Size of the boxes.
variant?OtpInputVariant | CustomVariant<"otpInput">"outline"Appearance: separate boxes ("outline"), joined boxes per group ("joined") or an underline ("underline"). Classes of a custom style added with defineAppearance are added to every box (in the outline layout if extends isn't given). If omitted, UIProvider appearance.defaults.otpInput.variant.
effect?EffectPropEffect or effects of the boxes (e.g. "lift", ["border", "beam"]). It plays on the next (to be typed) box; the accent color is the focus color. If omitted, UIProvider appearance.defaults.otpInput.effect. See BuiltinEffect.
webOtp?booleanfalseOn Android Chrome, fills the code from the SMS automatically with the user's consent (WebOTP). The last line of the SMS must be in the form @domain.com #123456. On iOS and other browsers the code is suggested above the keyboard thanks to autoComplete="one-time-code"; this prop isn't needed.
onResend?() => unknownIf given, a "Resend code" link appears under the boxes. On first display and after each send there is a countdown of OtpInputProps.resendDelay. If it returns a Promise it is awaited; if it throws, the countdown doesn't start. The boxes are cleared after a successful send.
resendDelay?number60Time to wait before resending (seconds).