data-mask

Format input values as the user types with preset masks for phone, credit card, date, and more. Supports custom patterns with digit, letter, and wildcard tokens.

Overview

The data-mask attribute formats input values in real time as the user types. Choose from preset masks for common formats or define custom patterns with digit, letter, and wildcard tokens.

How It Works

Add data-mask with a preset name or "custom" to any text input. The init script:

  1. Resolves the mask pattern from the preset name or data-pattern attribute
  2. Intercepts input events and reformats the value to match the pattern
  3. Manages cursor position so the caret stays in the correct place after reformatting
  4. Handles IME composition events (compositionstart / compositionend) to avoid interfering with multi-byte input
  5. Sets inputmode automatically ("numeric" for digit-only masks)
  6. Sets maxlength from the pattern length
  7. Stores the raw unformatted value in data-raw-value

The underlying input remains a real form control. The displayed value includes formatting characters, while data-raw-value provides the clean value for submission or processing.

Attributes

Attribute Type Description
data-mask string Preset name (phone, credit-card, date, ssn, zip) or custom.
data-pattern string Custom mask pattern. Required when data-mask="custom". Uses token characters for placeholders.
data-raw-value string Set automatically. Contains the unformatted input value (digits/letters only, no separators).
data-mask-init boolean Set automatically to prevent double-binding. Do not set manually.

Preset Masks

The following presets are available out of the box:

Value Pattern Example output
phone (###) ###-#### (555) 123-4567
credit-card #### #### #### #### 1234 5678 9012 3456
date ##/##/#### 01/15/2025
ssn ###-##-#### 123-45-6789
zip ##### 90210

Custom Patterns

Set data-mask="custom" and provide a data-pattern attribute with your own mask. Three token characters are supported:

Token Accepts Description
# Digit (0–9) Matches any single digit.
A Letter (a–z, A–Z) Matches any single letter. Output is uppercased.
* Any character Matches any single letter or digit. Output is uppercased.

Any other character in the pattern is treated as a literal separator and inserted automatically.

With Form Field

Wrap in <form-field> for validation feedback, helper text, and required indicators.

Raw Value

The data-raw-value attribute is updated on every input event and contains the unformatted value — digits and letters only, with no separators. Use it when submitting or processing the value.

Events

The masked input fires native input and change events. Access the raw value from data-raw-value in your event handler.

Dynamic Elements

Masked inputs added to the DOM after page load are automatically enhanced via a MutationObserver. No manual initialization is needed.