Author: | eduardovillao |
---|---|
Views Total: | 58 views |
Official Page: | Go to website |
Last Update: | January 24, 2025 |
License: | MIT |
Preview:

Description:
Dealing with input masks in web development can be tricky. You need to ensure users enter data in the correct format, but you don’t want to slow down your website with bulky scripts. That’s where Masky.js comes in. It is a tiny but powerful JavaScript library for handling input masking (like phone numbers, dates, or credit card numbers) in your web apps.
Masky.js lets you create various input masks. You can easily add prefixes and suffixes to your masks, and set up dynamic formatting to handle different input needs. Need to validate Brazilian CPF or CNPJ numbers? Masky.js has you covered with native validation support for these document types.
In addition, the library dynamically sets the inputmode
attribute, optimizing the keyboard layout for mobile users based on the mask. It also calculates and applies minlength
and maxlength
attributes based on your mask, reducing boilerplate and improving form validation.
How to use it:
1. Download Masky.js and include the minified script in your HTML:
<script src="masky.min.js"></script>
2. To apply a mask, use the data-mask
attribute on your input fields. Masky.js uses tokens to define the mask pattern:
- 0: Numeric digits only (0-9).
- A: Alphanumeric characters (a-zA-Z0-9).
- S: Alphabetic characters (a-zA-Z).
For example, to create a mask for a US phone number like (555) 555-1234, use the following:
<input type="text" data-mask="(000) 000-0000" />
3. Use data-mask-prefix
and data-mask-suffix
to include additional characters before or after the input:
<input type="text" data-mask="000-0000" data-mask-prefix="+01 " data-mask-suffix=" After" />
4. Masky.js supports built-in validation for CPF and CNPJ. Use the data-mask-validation
attribute:
// CPF validation: <input type="text" data-mask="000.000.000-00" data-mask-validation="cpf" />
// CNPJ validation: <input type="text" data-mask="00.000.000/0000-00" data-mask-validation="cnpj" />