Verification code input
A row of digit slots for a fixed-length code, backed by one real numeric input for paste, autofill and screen readers.
pnpm dlx shadcn@latest add @haze/otp-input---
import { cn } from "../../../lib/haze/utils";
import Input from "./input.astro";
interface Props {
id: string;
name?: string;
length?: number;
/** Draws a short dash between the two halves of an even-length code of 4 or more digits. */
separator?: boolean;
class?: string;
[key: string]: unknown;
}
const { id, name = id, length = 6, separator = true, class: className, ...rest } = Astro.props;
const digits = Number.isFinite(length) ? Math.min(12, Math.max(1, Math.trunc(length))) : 6;
const split = separator && digits >= 4 && digits % 2 === 0 ? digits / 2 : 0;
---
<div data-haze-otp dir="ltr" class={cn("group/otp relative w-full min-w-0", className)}>
<div aria-hidden="true" class="hidden items-center gap-2 group-data-enhanced/otp:flex group-has-[input:disabled]/otp:opacity-50">
{Array.from({ length: digits }, (_, index) => (
<>
<span data-otp-slot class="group/slot grid h-11 min-w-0 max-w-12 flex-1 place-items-center rounded-lg border border-frame-input bg-field font-mono text-base/6 tabular-nums text-muted-foreground transition-[border-color,box-shadow] duration-150 ease-snappy data-active:border-foreground data-active:ring-1 data-active:ring-foreground data-filled:text-foreground group-has-[input[aria-invalid=true]]/otp:border-destructive">
<span data-otp-char class="col-start-1 row-start-1"></span>
<span data-otp-caret class="col-start-1 row-start-1 hidden h-5 w-px bg-foreground group-data-caret/slot:block motion-safe:animate-blink"></span>
</span>
{split > 0 && index === split - 1 && <span class="h-px w-3 shrink-0 bg-border-strong"></span>}
</>
))}
</div>
<Input {...rest} id={id} name={name} type="text" inputmode="numeric" autocomplete="one-time-code"
dir="ltr" maxlength={digits} pattern={`[0-9]{${digits}}`}
class="h-11 font-mono text-[0.9375rem]/6 tracking-[0.28em] tabular-nums group-data-enhanced/otp:absolute group-data-enhanced/otp:inset-0 group-data-enhanced/otp:h-full group-data-enhanced/otp:cursor-text group-data-enhanced/otp:opacity-0" />
</div>
<script>
function enhance(root: HTMLElement) {
if (root.hasAttribute("data-enhanced")) return;
const input = root.querySelector<HTMLInputElement>("input");
if (!input) return;
root.setAttribute("data-enhanced", "");
const limit = input.maxLength > 0 ? input.maxLength : 12;
const digits = (text: string) => text.replace(/\D/g, "");
const emit = () => input.dispatchEvent(new Event("input", { bubbles: true }));
input.addEventListener("beforeinput", (event) => {
const data = event.data;
if (event.inputType === "insertText" && data && /\D/.test(data)) event.preventDefault();
});
input.addEventListener("paste", (event) => {
const text = event.clipboardData?.getData("text");
if (text === undefined || input.readOnly || input.disabled) return;
event.preventDefault();
const start = input.selectionStart ?? input.value.length;
const end = input.selectionEnd ?? start;
const room = limit - (input.value.length - (end - start));
const insert = digits(text).slice(0, Math.max(0, room));
if (!insert) return;
input.setRangeText(insert, start, end, "end");
emit();
});
input.addEventListener("input", () => {
const clean = digits(input.value).slice(0, limit);
if (clean !== input.value) {
const caret = (input.selectionStart ?? clean.length) - (input.value.length - clean.length);
input.value = clean;
input.setSelectionRange(Math.max(0, Math.min(caret, clean.length)), Math.max(0, Math.min(caret, clean.length)));
}
});
const slots = [...root.querySelectorAll<HTMLElement>("[data-otp-slot]")];
const hint = input.placeholder;
const paint = () => {
const focused = document.activeElement === input;
const at = Math.min(input.selectionStart ?? input.value.length, slots.length - 1);
slots.forEach((slot, index) => {
const char = input.value[index] ?? "";
const view = slot.querySelector<HTMLElement>("[data-otp-char]");
const shown = char || hint[index] || "";
if (view && view.textContent !== shown) view.textContent = shown;
slot.toggleAttribute("data-filled", Boolean(char));
slot.toggleAttribute("data-active", focused && index === at);
slot.toggleAttribute("data-caret", focused && index === at && !char);
});
};
for (const type of ["input", "focus", "blur", "keyup", "pointerup", "select"]) input.addEventListener(type, paint);
input.addEventListener("focus", () => queueMicrotask(() => {
if (input.selectionStart === input.selectionEnd) input.setSelectionRange(input.value.length, input.value.length);
paint();
}));
// The real input is stretched over the slots, so map the click to a slot instead of a text offset.
input.addEventListener("mousedown", (event) => {
if (event.button !== 0 || input.disabled) return;
event.preventDefault();
const at = slots.findIndex((slot) => event.clientX <= slot.getBoundingClientRect().right);
const index = Math.min(at < 0 ? slots.length - 1 : at, input.value.length);
input.focus();
input.setSelectionRange(index, index < input.value.length ? index + 1 : index);
paint();
});
input.form?.addEventListener("reset", () => queueMicrotask(paint));
paint();
}
const init = () => document.querySelectorAll<HTMLElement>("[data-haze-otp]").forEach(enhance);
init();
if (!document.documentElement.hasAttribute("data-haze-otp-listener")) {
document.documentElement.setAttribute("data-haze-otp-listener", "");
document.addEventListener("astro:page-load", init);
}
</script>When to use
- An authenticator app or message supplies a short numeric code
- A leading zero must survive paste and form submission
When not to use
- The credential contains letters or separators. Use input and specify its format.
Installation
Add the Haze registry to components.json once, then install Verification code input with the shadcn CLI. Works in any Astro project with Tailwind CSS v4.
pnpm dlx shadcn@latest add @haze/otp-inputnpx shadcn@latest add @haze/otp-inputyarn dlx shadcn@latest add @haze/otp-inputbunx --bun shadcn@latest add @haze/otp-inputFirst time? Registry and theme setup
1. Add to components.json:
{
"registries": {
"@haze": "http://localhost:4329/r/{name}.json"
}
}2. Install the theme once: npx shadcn@latest add @haze/theme, then import it after Tailwind in your global CSS:@import "./haze.css";
API reference
| Prop | Type | Default | Description |
|---|---|---|---|
| id* | string | – | Unique control ID. Use it to associate a label with the input. |
| name | string | id | Form field name. |
| length | number | 6 | Expected number of digits, between 1 and 12. |
| separator | boolean | true | Draws a dash between the halves of an even-length code of 4 digits or more. |
| ...attributes | HTML input attributes | – | Additional attributes for the native input. |
| class | string | – | Additional classes on the wrapper. |
Keyboard interactions
- Tab
- Focus the whole verification code.
- Paste
- Insert the code as a single string.
Accessibility
- Associate a visible label and state the expected length outside the field.
- Digit boxes are decorative and hidden from assistive technology; the code is one text input with native format validation, and without scripts it shows as a plain field. Supply required when a blank code is invalid.
Notes for AI
Copy into Claude Code, Cursor, Codex or any coding agent. Agents can also read the Markdown version of this page.
Install and use
Install the Haze UI component "Verification code input" with `npx shadcn@latest add @haze/otp-input`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "http://localhost:4329/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import OtpInput from "@/components/haze/ui/otp-input.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: http://localhost:4329/ui/otp-input.md
Customize with real content
Adapt the Haze otp-input ui for our product. Replace the demo values of these props with our real content: id, name, length, separator, ...attributes, class. Keep the layout, the heading level rules and these accessibility details: Associate a visible label and state the expected length outside the field. Digit boxes are decorative and hidden from assistive technology; the code is one text input with native format validation, and without scripts it shows as a plain field. Supply required when a blank code is invalid. Do not add raw color classes; use the Haze tokens.
Choose the right block
Before using otp-input, check it fits: use it when an authenticator app or message supplies a short numeric code; a leading zero must survive paste and form submission. Avoid it when the credential contains letters or separators. use input and specify its format.. Alternatives: @haze/input, @haze/password-input.
Dependencies
- @haze/input
- @haze/utils
- @haze/theme (one-time setup)
Source · Original Haze UI work.