Files
tabler/docs/content/ui/plugins/input-mask.mdx
T

75 lines
2.7 KiB
Plaintext

---
title: Input mask
order: 11
summary: An input mask is used to clarify the input format required in a given field and is helpful for users, removing confusion and reducing the number of validation errors.
description: Format user input automatically with input masks for dates, phone numbers, and other patterns to reduce validation errors.
docs-libs: [imask]
related: [/ui/forms/elements]
---
import Example from '@components/Example.astro'
import TabsPackage from '@components/TabsPackage.astro'
import CodeDocs from '@components/CodeDocs.astro';
## Installation
To be able to use the input mask in your application you will need to install the imask dependency. You can do this by running the following command:
<TabsPackage name="imask" />
And import or require:
```javascript
import IMask from 'imask'
```
You can also use the CDN link to include the script in your project:
```html
<script src="https://cdn.jsdelivr.net/npm/imask"></script>
```
If you struggle with the installation, you can find more information in the [IMask documentation](https://imask.js.org/guide.html#installation).
## Default markup
Use an input mask in the fields where users have to enter their phone number, to make the formatting rules clear and help them avoid confusion.
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"
/>
```
Look at the example below to see how the input mask works:
<Example column>
<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" />
</Example>
## 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:
<CodeDocs name="input-mask-init" file="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.