Quick start
Turn a text input into a phone field that formats as you type.
This example uses TypeScript in a bundled app. Using a UI framework? Choose your framework. For a plain HTML page, use the CDN guide.
1. Install#
npm install mother-mask2. Add a phone input#
Add a label and an empty text input to your page. The module script loads your code after the HTML has been parsed.
<label for="phone">Phone number</label>
<input
id="phone"
name="phone"
type="text"
inputmode="tel"
autocomplete="tel"
placeholder="(11) 98765-4321"
/>
<script type="module" src="/src/main.ts"></script>3. Bind the mask#
In src/main.ts, select the input and give it a pattern. Each 9 accepts a digit; parentheses, spaces, and the dash are added for you.
import { bind } from 'mother-mask'
const phone = document.querySelector<HTMLInputElement>('#phone')!
const dispose = bind(phone, '(99) 99999-9999')Type 11987654321 to get (11) 98765-4321. You can also paste a number or edit it in place.
A mask controls formatting. Check separately whether the phone number is valid.
When you need more#
Start with an existing value
Binding formats user edits. To prefill the field or set its value from code, format the value with process(). Add this to the same module:
import { process } from 'mother-mask'
// Use the same pattern as your binding.
phone.value = process('11987654321', '(99) 99999-9999')
// \u2192 (11) 98765-4321Clean up when the input is removed
Keep the dispose function returned by bind() and call it in your page or component cleanup. Call it before binding a different mask to the same input, too.
// Run when your page or component is removed.
dispose()Next, explore more live examples, format currency and decimals, or see callbacks and options in the API reference.