Skip to content

MaskedInput

Form

Digit-only formatted entry with raw values and caret-aware separator editing.

Prefixed invoice referencePartial postal formatSeparator deletion and pasteDisabled reference
Open preview

Responsive viewport — resize the window to explore. Direction and density apply only to this preview. Theme applies to the docs too.

Usage

Use # for digit slots and non-digit literals for prefixes/separators, such as INV-####-####. The controlled value and callback contain only digits, while the visible input contains the formatting. Extra digits are truncated to capacity. Backspace/Delete at a separator remove the adjacent digit rather than trapping the caret. Partial values are allowed; the mask does not validate dates, addresses, payment information, or business rules. Patterns containing literal digits or no slots disable entry with guidance.

Import
import { MaskedInput } from "@/components/ui/masked-input";

Shipped as editable source in src/components/ui/masked-input.tsx in both apps. Copy the implementation below when moving it to another project. Copy the complete example from Source code for all imports and state. Add "use client" when using hooks or event handlers. See installation and theming for project setup.

Component source

The complete implementation is included in both apps. It uses the React, Radix, Lucide, and shared-core dependencies already installed in Apex. Keep your project’s semantic theme tokens when reusing it.

src/components/ui/masked-input.tsx
"use client";
import { useId, useRef, type KeyboardEvent } from "react";
import { Label } from "@dashboardpack/core/components/ui/label";
import { cn } from "@dashboardpack/core/lib/utils";
export function maskCapacity(pattern: string) {
  return (pattern.match(/#/g) ?? []).length;
}
export function formatMaskedValue(value: string, pattern: string) {
  const digits = value.replace(/\D/g, "").slice(0, maskCapacity(pattern));
  if (!digits) return "";
  let index = 0;
  let output = "";
  for (const token of pattern) {
    if (index >= digits.length) break;
    output += token === "#" ? digits[index++] : token;
  }
  return output;
}
function caretAfterDigits(text: string, count: number) {
  if (count <= 0) {
    const first = text.search(/\d/);
    return first < 0 ? text.length : first;
  }
  let digits = 0;
  for (let index = 0; index < text.length; index++)
    if (/\d/.test(text[index]) && ++digits === count) return index + 1;
  return text.length;
}
export interface MaskedInputProps {
  label: string;
  pattern: string;
  value: string;
  onValueChange: (digits: string) => void;
  name?: string;
  disabled?: boolean;
  hint?: string;
  className?: string;
}
export function MaskedInput({
  label,
  pattern,
  value,
  onValueChange,
  name,
  disabled,
  hint,
  className,
}: MaskedInputProps) {
  const id = useId();
  const input = useRef<HTMLInputElement>(null);
  const valid = maskCapacity(pattern) > 0 && !/[0-9]/.test(pattern);
  const digits = value.replace(/\D/g, "").slice(0, maskCapacity(pattern));
  const formatted = formatMaskedValue(digits, pattern);
  const update = (next: string, caretDigits: number) => {
    onValueChange(next);
    requestAnimationFrame(() => {
      const position = caretAfterDigits(
        formatMaskedValue(next, pattern),
        caretDigits,
      );
      input.current?.setSelectionRange(position, position);
    });
  };
  const erase = (event: KeyboardEvent<HTMLInputElement>) => {
    if (event.nativeEvent.isComposing) return;
    const node = event.currentTarget;
    const start = node.selectionStart ?? 0;
    const end = node.selectionEnd ?? start;
    if (start !== end) return;
    if (
      event.key === "Backspace" &&
      start > 0 &&
      !/\d/.test(formatted[start - 1] ?? "")
    ) {
      const before = formatted.slice(0, start).replace(/\D/g, "").length;
      if (before) {
        event.preventDefault();
        update(digits.slice(0, before - 1) + digits.slice(before), before - 1);
      }
    }
    if (
      event.key === "Delete" &&
      start < formatted.length &&
      !/\d/.test(formatted[start] ?? "")
    ) {
      const before = formatted.slice(0, start).replace(/\D/g, "").length;
      event.preventDefault();
      update(digits.slice(0, before) + digits.slice(before + 1), before);
    }
  };
  return (
    <div className={cn("min-w-0 space-y-2", className)}>
      <Label htmlFor={id}>{label}</Label>
      <input
        ref={input}
        id={id}
        value={formatted}
        inputMode="numeric"
        dir="ltr"
        type="text"
        disabled={disabled || !valid}
        placeholder={pattern.replace(/#/g, "_")}
        aria-describedby={`${id}-hint`}
        onKeyDown={erase}
        onChange={(event) => {
          const next = event.target.value
            .replace(/\D/g, "")
            .slice(0, maskCapacity(pattern));
          const count = event.target.value
            .slice(0, event.target.selectionStart ?? 0)
            .replace(/\D/g, "").length;
          update(next, count);
        }}
        className="h-10 w-full rounded-lg border border-input bg-background px-3 font-mono text-sm outline-none focus-visible:ring-2 focus-visible:ring-ring disabled:opacity-50"
      />
      {name && (
        <input
          type="hidden"
          name={name}
          value={digits}
          disabled={disabled || !valid}
        />
      )}
      <p id={`${id}-hint`} className="text-xs text-muted-foreground">
        {!valid
          ? "Use # for digit slots and non-digit characters for separators."
          : (hint ?? `Format: ${pattern}. Only digits are stored.`)}
      </p>
    </div>
  );
}

API reference

Common props and defaults. Slot-specific props are named below; native elements also accept their standard HTML attributes. The component TypeScript definitions are the complete type reference.

MaskedInput props
PropType / DefaultDescription
labelstring

Default: required

Visible accessible field label.
patternstring

Default: required

Digit slots (#) with non-digit literals.
valuestring

Default: required

Controlled digit string.
onValueChange(digits: string) => void

Default: required

Apply raw digit edits.
namestring

Default: —

Emit a hidden native form field containing the raw digits.
hintstring

Default: format guidance

Override the helper text for valid patterns.
disabledboolean

Default: false

Disable editing and hidden-field submission.
classNamestring

Default: —

Extend the container with semantic theme utilities.

Build with these too