# Input mask

> An input mask formats what the user types to a pattern, such as a phone number or a date, which makes the expected format clear and cuts validation errors.

Format user input automatically with input masks for dates, phone numbers, and other patterns to reduce validation errors.

Source: https://docs.tabler.io/ui/plugins/input-mask

---

## Installation

Install the imask library:

```shell
npm install imask
yarn add imask
pnpm install imask
bun install imask
```

And import or require:

```javascript
import IMask from 'imask'
```

Or include it from a CDN:

```html
<script src="https://cdn.jsdelivr.net/npm/imask"></script>
```

The [IMask documentation](https://imask.js.org/guide.html#installation) covers other ways to install it.

## Default markup

Use an input mask where the value has a fixed format, such as a phone number, a date or a card number.

To create an input mask, add the `data-mask` attribute to the input element:

```html
<input
  type="text"
  name="input-mask"
  class="form-control"
  data-mask="(00) 0000-0000"
  placeholder="(00) 0000-0000"
  autocomplete="off"
/>
```

```html
<label class="form-label">Telephone mask</label>
<label class="form-label" for="mask-phone">Phone number</label>
<input type="text" id="mask-phone" name="input-mask" class="form-control" data-mask="(00) 0000-0000" data-mask-visible="true" placeholder="(00) 0000-0000" autocomplete="off" />
```

## More examples

If you need more examples of input masks, you can find them in the [IMask documentation](https://imask.js.org/guide.html#masked-input).

## JavaScript

Tabler automatically initializes all elements with `data-mask` on page load. This is the code that runs:

```ts
const maskElementList: HTMLElement[] = [].slice.call(document.querySelectorAll<HTMLElement>('[data-mask]'))
maskElementList.map(function (maskEl: HTMLElement) {
  window.IMask &&
    new window.IMask(maskEl, {
      mask: maskEl.dataset.mask,
      lazy: maskEl.dataset.maskVisible !== 'true',
    })
})
```

_Source: `core/js/src/input-mask.ts`_

## Accessibility

- A mask changes what the field accepts as the user types, which is easy to lose track of without sight. Say the expected format in a hint tied to the field with `aria-describedby`.
- Keep a real `label`. The placeholder shows the pattern, and it disappears as soon as typing starts.
- Do not block paste. A masked field that rejects a pasted phone number is a dead end for anyone using a password manager or a switch device.
- Use the right `type` and `autocomplete`, so the browser can still fill the field and the phone keyboard matches.
