IMask.js

7.6.1 · active · verified Sun Apr 19

IMask.js is a robust vanilla JavaScript input mask library that dynamically formats user input in form fields, ensuring data consistency and improving user experience. It supports a wide array of mask types including pattern, number, date, range, enum, and dynamic masks, and allows for custom definitions and repeating blocks. The library is currently in active development, with version 7.6.1 being the latest stable release, featuring frequent minor updates to address bugs and introduce enhancements like autofix options and improved IME support. A key differentiator is its framework-agnostic core, accompanied by dedicated plugins for popular frameworks such as React, Vue, Angular, Svelte, and Solid, enabling consistent masking behavior across various JavaScript ecosystems. It has no external dependencies and is designed for broad browser compatibility.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates setting up two common masks: a phone number using a pattern mask and a currency input using a number mask. It highlights basic initialization, options like `lazy` and `placeholderChar`, and how to access `value` and `unmaskedValue`.

import IMask from 'imask';

document.addEventListener('DOMContentLoaded', () => {
  const phoneInput = document.getElementById('phone-input');
  if (phoneInput) {
    const phoneMask = IMask(phoneInput, {
      mask: '+{7}(000)000-00-00',
      lazy: false, // show placeholder from start
      placeholderChar: '_'
    });
    
    // Example of accessing values
    phoneInput.addEventListener('blur', () => {
      console.log('Masked Value:', phoneMask.value);
      console.log('Unmasked Value:', phoneMask.unmaskedValue);
    });
  }

  const currencyInput = document.getElementById('currency-input');
  if (currencyInput) {
    const currencyMask = IMask(currencyInput, {
      mask: Number,
      thousandsSeparator: ' ',
      scale: 2, // digits after point
      signed: false, // disallow negative
      padFractionalZeros: true, // if true, then pads zeros at end to the length of scale
      normalizeZeros: true, // appends or removes zeros at the end of the fractional part of a number
      mapToRadix: ['.', ','], // to change radix point for `.` or `,` from keyboard
      radix: '.', // fractional delimiter
      autofix: true // automatically fix incomplete input
    });
  }
});

// To make this runnable in a browser, you'd need HTML like:
// <input type="text" id="phone-input" placeholder="+7(___)___-__-__">
// <input type="text" id="currency-input" placeholder="0.00">

view raw JSON →