For the complete documentation index, see llms.txt. Markdown variants are available by appending .md to any URL or sending an Accept: text/markdown header. An agent skill is available at /.well-known/agent-skills/site-skill.md.
FrakmentFrakment

Input OTP

Accessible one-time password input with configurable length and pattern.

Web
Frakment
1
2
3
4
5
6
input-otp.tsx
"use client";

import { MinusIcon } from "lucide-react";
import * as React from "react";
import { cn } from "@/lib/utils";

const digits = "^\\d+$";
const chars = "^[a-zA-Z]+$";
const alphanumeric = "^[a-zA-Z0-9]+$";

interface SlotProps {
  char: string | null;
  hasFakeCaret: boolean;
  isActive: boolean;
  placeholderChar: string | null;
}

interface RenderProps {
  isFocused: boolean;
  isHovering: boolean;
  slots: SlotProps[];
}

const OTPInputContext = React.createContext<RenderProps>({
  isFocused: false,
  isHovering: false,
  slots: [],
});

type OTPInputBaseProps = Omit<
  React.InputHTMLAttributes<HTMLInputElement>,
  "value" | "onChange" | "maxLength" | "pattern" | "placeholder"
> & {
  containerClassName?: string;
  maxLength: number;
  onChange?: (value: string) => void;
  pattern?: string;
  placeholder?: string;
  value?: string;
};

type OTPInputProps = OTPInputBaseProps & {
  children?: React.ReactNode;
};

const InputOTP = React.forwardRef<HTMLInputElement, OTPInputProps>(
  function InputOTP(
    {
      children,
      className,
      containerClassName,
      defaultValue,
      disabled,
      id,
      inputMode = "numeric",
      maxLength,
      onChange,
      onFocus,
      onBlur,
      pattern,
      placeholder,
      value: valueProp,
      ...props
    },
    forwardedRef
  ) {
    const isControlled = valueProp !== undefined;
    const [uncontrolled, setUncontrolled] = React.useState<string>(
      typeof defaultValue === "string" ? defaultValue : ""
    );
    const value = isControlled ? valueProp : uncontrolled;
    const [isFocused, setIsFocused] = React.useState(false);
    const [isHovering, setIsHovering] = React.useState(false);
    const [selectionStart, setSelectionStart] = React.useState(0);
    const [selectionEnd, setSelectionEnd] = React.useState(0);
    const inputRef = React.useRef<HTMLInputElement>(null);

    const setRef = React.useCallback(
      (node: HTMLInputElement | null) => {
        inputRef.current = node;
        if (typeof forwardedRef === "function") {
          forwardedRef(node);
        } else if (forwardedRef) {
          (
            forwardedRef as React.MutableRefObject<HTMLInputElement | null>
          ).current = node;
        }
      },
      [forwardedRef]
    );

    const filterValue = React.useCallback(
      (raw: string): string => {
        let next = raw.slice(0, maxLength);
        if (pattern) {
          const re = new RegExp(pattern);
          if (!re.test(next)) {
            next = next
              .split("")
              .filter((c) => new RegExp(pattern.replace(/[+*]$/, "")).test(c))
              .join("");
          }
        }
        return next;
      },
      [maxLength, pattern]
    );

    const commit = React.useCallback(
      (next: string) => {
        const filtered = filterValue(next);
        if (!isControlled) {
          setUncontrolled(filtered);
        }
        onChange?.(filtered);
      },
      [filterValue, isControlled, onChange]
    );

    const updateSelection = React.useCallback(() => {
      const el = inputRef.current;
      if (!el) {
        return;
      }
      setSelectionStart(el.selectionStart ?? 0);
      setSelectionEnd(el.selectionEnd ?? 0);
    }, []);

    const slots = React.useMemo<SlotProps[]>(
      () =>
        Array.from({ length: maxLength }).map((_, i) => {
          const char = value[i] ?? null;
          const active =
            isFocused &&
            ((selectionStart === selectionEnd && i === selectionStart) ||
              (i >= selectionStart && i < selectionEnd));
          return {
            char,
            hasFakeCaret: active && char === null,
            isActive: active,
            placeholderChar: null,
          };
        }),
      [value, maxLength, isFocused, selectionStart, selectionEnd]
    );

    const contextValue = React.useMemo<RenderProps>(
      () => ({ isFocused, isHovering, slots }),
      [isFocused, isHovering, slots]
    );

    const handleInput = (event: React.ChangeEvent<HTMLInputElement>) => {
      commit(event.currentTarget.value);
      updateSelection();
    };

    const handleSelect = () => updateSelection();

    const handleClick = () => {
      inputRef.current?.focus();
      updateSelection();
    };

    const handleKeyDown = (event: React.KeyboardEvent<HTMLInputElement>) => {
      props.onKeyDown?.(event);
      if (event.defaultPrevented) {
        return;
      }
      requestAnimationFrame(updateSelection);
    };

    return (
      <OTPInputContext.Provider value={contextValue}>
        <div
          className={cn("cn-input-otp flex items-center", containerClassName)}
          data-slot="input-otp"
          onClick={handleClick}
          onMouseEnter={() => setIsHovering(true)}
          onMouseLeave={() => setIsHovering(false)}
        >
          <input
            aria-label={props["aria-label"] ?? "One-time password"}
            autoComplete="one-time-code"
            className={cn(
              "pointer-events-none absolute inset-0 -z-10 opacity-0",
              className
            )}
            data-input-otp=""
            defaultValue={
              isControlled ? undefined : (defaultValue as string | undefined)
            }
            disabled={disabled}
            id={id}
            inputMode={inputMode}
            maxLength={maxLength}
            onBlur={(e) => {
              setIsFocused(false);
              onBlur?.(e);
            }}
            onChange={handleInput}
            onFocus={(e) => {
              setIsFocused(true);
              updateSelection();
              onFocus?.(e);
            }}
            onKeyDown={handleKeyDown}
            onSelect={handleSelect}
            pattern={pattern}
            placeholder={placeholder}
            ref={setRef}
            value={isControlled ? value : undefined}
            {...props}
          />
          {children}
        </div>
      </OTPInputContext.Provider>
    );
  }
);

function InputOTPGroup({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      className={cn(
        "has-aria-invalid:border-destructive has-aria-invalid:ring-destructive/20 dark:has-aria-invalid:ring-destructive/40 flex items-center rounded-lg has-aria-invalid:ring-3",
        className
      )}
      data-slot="input-otp-group"
      {...props}
    />
  );
}

function InputOTPSlot({
  index,
  className,
  ...props
}: React.ComponentProps<"div"> & { index: number }) {
  const inputOTPContext = React.useContext(OTPInputContext);
  const { char, hasFakeCaret, isActive } = inputOTPContext.slots[index] ?? {};

  return (
    <div
      className={cn(
        "border-input aria-invalid:border-destructive data-[active=true]:border-ring data-[active=true]:ring-ring/50 data-[active=true]:aria-invalid:border-destructive data-[active=true]:aria-invalid:ring-destructive/20 dark:bg-input/30 dark:data-[active=true]:aria-invalid:ring-destructive/40 relative flex size-8 items-center justify-center border-y border-r text-sm transition-all outline-none first:rounded-l-lg first:border-l last:rounded-r-lg data-[active=true]:z-10 data-[active=true]:ring-3",
        className
      )}
      data-active={isActive}
      data-slot="input-otp-slot"
      {...props}
    >
      {char}
      {hasFakeCaret && (
        <div className="pointer-events-none absolute inset-0 flex items-center justify-center">
          <div className="animate-caret-blink bg-foreground h-4 w-px duration-1000" />
        </div>
      )}
    </div>
  );
}

function InputOTPSeparator({ ...props }: React.ComponentProps<"div">) {
  return (
    <div
      className="flex items-center [&_svg:not([class*='size-'])]:size-4"
      data-slot="input-otp-separator"
      role="separator"
      {...props}
    >
      <MinusIcon />
    </div>
  );
}

export {
  alphanumeric,
  chars,
  digits,
  InputOTP,
  InputOTPGroup,
  InputOTPSeparator,
  InputOTPSlot,
};

Input OTP renders a one-time password field with real input handling for paste, backspace, and arrow keys. Each slot is a separate visual box, but the underlying input is a single element for form submission.

Installation

Usage

input-otp.tsx
import {
  InputOTP,
  InputOTPGroup,
  InputOTPSeparator,
  InputOTPSlot,
} from "@/components/ui/input-otp";
tsx
<InputOTP maxLength={6}>
  <InputOTPGroup>
    <InputOTPSlot index={0} />
    <InputOTPSlot index={1} />
    <InputOTPSlot index={2} />
  </InputOTPGroup>
  <InputOTPSeparator />
  <InputOTPGroup>
    <InputOTPSlot index={3} />
    <InputOTPSlot index={4} />
    <InputOTPSlot index={5} />
  </InputOTPGroup>
</InputOTP>

Examples

Pattern

digits restricts input to numbers.

input-otp-pattern.tsx
"use client";

import { Field, FieldLabel } from "@/components/ui/field";
import {
  digits,
  InputOTP,
  InputOTPGroup,
  InputOTPSlot,
} from "@/components/ui/input-otp";

export function InputOTPPattern() {
  return (
    <Field className="w-fit">
      <FieldLabel htmlFor="digits-only">Digits Only</FieldLabel>
      <InputOTP id="digits-only" maxLength={6} pattern={digits}>
        <InputOTPGroup>
          <InputOTPSlot index={0} />
          <InputOTPSlot index={1} />
          <InputOTPSlot index={2} />
          <InputOTPSlot index={3} />
          <InputOTPSlot index={4} />
          <InputOTPSlot index={5} />
        </InputOTPGroup>
      </InputOTP>
    </Field>
  );
}

With separator

input-otp-separator.tsx
import {
  InputOTP,
  InputOTPGroup,
  InputOTPSeparator,
  InputOTPSlot,
} from "@/components/ui/input-otp";

export function InputOTPWithSeparator() {
  return (
    <InputOTP maxLength={6}>
      <InputOTPGroup>
        <InputOTPSlot index={0} />
        <InputOTPSlot index={1} />
      </InputOTPGroup>
      <InputOTPSeparator />
      <InputOTPGroup>
        <InputOTPSlot index={2} />
        <InputOTPSlot index={3} />
      </InputOTPGroup>
      <InputOTPSeparator />
      <InputOTPGroup>
        <InputOTPSlot index={4} />
        <InputOTPSlot index={5} />
      </InputOTPGroup>
    </InputOTP>
  );
}

Controlled

Drive the value from your own state.

Enter your one-time password.
input-otp-controlled.tsx
"use client";

import * as React from "react";
import {
  InputOTP,
  InputOTPGroup,
  InputOTPSlot,
} from "@/components/ui/input-otp";

export function InputOTPControlled() {
  const [value, setValue] = React.useState("");
  return (
    <div className="space-y-2">
      <InputOTP maxLength={6} onChange={setValue} value={value}>
        <InputOTPGroup>
          <InputOTPSlot index={0} />
          <InputOTPSlot index={1} />
          <InputOTPSlot index={2} />
          <InputOTPSlot index={3} />
          <InputOTPSlot index={4} />
          <InputOTPSlot index={5} />
        </InputOTPGroup>
      </InputOTP>
      <div className="text-center text-sm">
        {value === "" ? (
          <>Enter your one-time password.</>
        ) : (
          <>You entered: {value}</>
        )}
      </div>
    </div>
  );
}

Invalid

Set aria-invalid on slots to mark them invalid.

0
0
0
0
0
0
input-otp-invalid.tsx
"use client";

import * as React from "react";
import {
  InputOTP,
  InputOTPGroup,
  InputOTPSeparator,
  InputOTPSlot,
} from "@/components/ui/input-otp";

export function InputOTPInvalid() {
  const [value, setValue] = React.useState("000000");
  return (
    <InputOTP maxLength={6} onChange={setValue} value={value}>
      <InputOTPGroup>
        <InputOTPSlot aria-invalid index={0} />
        <InputOTPSlot aria-invalid index={1} />
      </InputOTPGroup>
      <InputOTPSeparator />
      <InputOTPGroup>
        <InputOTPSlot aria-invalid index={2} />
        <InputOTPSlot aria-invalid index={3} />
      </InputOTPGroup>
      <InputOTPSeparator />
      <InputOTPGroup>
        <InputOTPSlot aria-invalid index={4} />
        <InputOTPSlot aria-invalid index={5} />
      </InputOTPGroup>
    </InputOTP>
  );
}

Alphanumeric

alphanumeric allows letters and numbers.

input-otp-alphanumeric.tsx
"use client";

import {
  alphanumeric,
  InputOTP,
  InputOTPGroup,
  InputOTPSeparator,
  InputOTPSlot,
} from "@/components/ui/input-otp";

export function InputOTPAlphanumeric() {
  return (
    <InputOTP maxLength={6} pattern={alphanumeric}>
      <InputOTPGroup>
        <InputOTPSlot index={0} />
        <InputOTPSlot index={1} />
        <InputOTPSlot index={2} />
      </InputOTPGroup>
      <InputOTPSeparator />
      <InputOTPGroup>
        <InputOTPSlot index={3} />
        <InputOTPSlot index={4} />
        <InputOTPSlot index={5} />
      </InputOTPGroup>
    </InputOTP>
  );
}

Disabled

1
2
3
4
5
6
input-otp-disabled.tsx
import {
  InputOTP,
  InputOTPGroup,
  InputOTPSeparator,
  InputOTPSlot,
} from "@/components/ui/input-otp";

export function InputOTPDisabled() {
  return (
    <InputOTP disabled id="disabled" maxLength={6} value="123456">
      <InputOTPGroup>
        <InputOTPSlot index={0} />
        <InputOTPSlot index={1} />
        <InputOTPSlot index={2} />
      </InputOTPGroup>
      <InputOTPSeparator />
      <InputOTPGroup>
        <InputOTPSlot index={3} />
        <InputOTPSlot index={4} />
        <InputOTPSlot index={5} />
      </InputOTPGroup>
    </InputOTP>
  );
}

Four digits

input-otp-four-digits.tsx
"use client";

import {
  digits,
  InputOTP,
  InputOTPGroup,
  InputOTPSlot,
} from "@/components/ui/input-otp";

export function InputOTPFourDigits() {
  return (
    <InputOTP maxLength={4} pattern={digits}>
      <InputOTPGroup>
        <InputOTPSlot index={0} />
        <InputOTPSlot index={1} />
        <InputOTPSlot index={2} />
        <InputOTPSlot index={3} />
      </InputOTPGroup>
    </InputOTP>
  );
}

In Context

Verification code

input-otp-verification.tsx
import {
  InputOTP,
  InputOTPGroup,
  InputOTPSeparator,
  InputOTPSlot,
} from "@/components/ui/input-otp";
import { Label } from "@/components/ui/label";

export function InputOTPVerification() {
  return (
    <div className="mx-auto flex w-full max-w-sm flex-col items-center gap-2">
      <Label>Verification code</Label>
      <InputOTP maxLength={6}>
        <InputOTPGroup>
          <InputOTPSlot index={0} />
          <InputOTPSlot index={1} />
          <InputOTPSlot index={2} />
        </InputOTPGroup>
        <InputOTPSeparator />
        <InputOTPGroup>
          <InputOTPSlot index={3} />
          <InputOTPSlot index={4} />
          <InputOTPSlot index={5} />
        </InputOTPGroup>
      </InputOTP>
    </div>
  );
}

API Reference

InputOTP

PropTypeDefaultDescription
maxLengthnumber—Number of character slots.
valuestring—Controlled value.
onChangefunction—Called with the new value.
patternstring—Regex string that limits allowed characters.
disabledbooleanfalsePrevent input.
containerClassNamestring—Applied to the input container.

InputOTPSlot

PropTypeDefaultDescription
indexnumber—Position of this slot within the input.

Controlled

tsx
const [value, setValue] = React.useState("")
<InputOTP value={value} onChange={setValue} maxLength={6}>{/* ... */}</InputOTP>

States

StateHow
Emptydefault
Partialsome slots filled
Completeall slots filled
Invalidaria-invalid="true"

Keyboard

KeyAction
← / →Move between slots
BackspaceDelete and move back
Ctrl + V / Cmd + VPaste the full code

Data Attributes

AttributeValues
data-slotinput-otp, input-otp-group, input-otp-slot, input-otp-separator
data-activetrue (caret in this slot)

Accessibility

  • The wrapper renders a real <input> with inputmode="numeric" for mobile keyboards.
  • Slots expose data-active and data-invalid for styling, but the input itself carries aria-invalid.
  • Paste, backspace, and arrow navigation are handled automatically.
  • Pair with FieldLabel htmlFor and id for labelled forms.

Best Practices

  • Use maxLength matching the code length. Do not let the input grow arbitrarily.
  • Group visually, not semantically. 3 + 3 reads better than 6 in one row.
  • Auto-focus the first slot on mount. Reduces taps on mobile.
  • Paste support is required. Users copy codes from messages; paste should fill every slot.