Add data-mask to a text field
so what people type takes a pattern, such as a phone or card number.
The mask goes on an <input> of type text,
tel, search, url or password,
the types with a caret. AutoInit() starts every one. Show the
expected format in the supporting text, and add
inputmode="numeric" to a digit-only mask so phones open a number pad.
<div class="field">
<input id="phone" name="phone" type="tel" inputmode="numeric" autocomplete="tel-national"
placeholder=" " data-mask="(000) 000-0000" aria-describedby="phone_help">
<label for="phone">Phone</label>
<small id="phone_help">Format: (555) 123-4567</small>
</div>
Mask syntax
In the mask, 0 takes a digit, a takes a letter and
* takes either. Every other character is a literal the mask
writes itself. A backslash makes the next character a literal, so
\0 writes a zero and \a writes an a.
Typing, pasting and deleting
Each character that fits fills the next slot, and the mask writes the
literals that come before it: typing 5551 into
(000) 000-0000 shows (555) 1. A character that fits
no slot is dropped, as is one past the end. A paste or autofill keeps the
characters that fit and skips the rest, so 555.123.4567 becomes
(555) 123-4567. The caret stays after the last character the
edit added.
A typed character matches only the literal that comes next, so in a
+1 (000) 000-0000 mask a typed leading 1 fills the first slot.
A paste or autofill that starts with +1 matches the prefix.
Leave a country code out of the mask, or say in the supporting text not to
type it. A mask with no slot leaves the field alone.
Backspace right after a literal, or Delete right before one, removes the digit across it, and the digits after it move back. Keypad keys format like typing; with the caret right after a literal, its Backspace moves the caret before the literal, and a second press deletes the digit. After a formatted edit, undo does not step back, because setting the value clears the field's undo history.
The submitted value
The form submits the value as the field shows it, and pattern,
required and the length checks run on that value. A saved value
is formatted when the component starts, without an input or
change event, and again after a form reset. The component formats
before the page's own input listeners run, so they read the
formatted value. A value a script sets is formatted once the script fires an
input event. In a right-to-left page, add dir="ltr"
to a phone or card number field.
IME composition
While an input method editor composes, the field keeps what it writes and formats once the composition ends. Full-width digits count as digits. Android keyboards can treat ordinary typing as composition, so a letter mask there may format only when a word ends; a number pad does not compose.
Methods
const mask = Expressive.InputMask.getInstance(document.getElementById('phone'));
mask.destroy(); // removes the listeners and leaves the value as it is