Input Masking and Validation JavaScript Library

Marcelo Ribeiro January 20, 2023


Live Preview Download

Smask is a developer-friendly input mask JavaScript library that helps format & validate values (like currency values, and phone numbers) as a user types in an input field.

Smask JavaScript Library Implementation

Import needed modules from the smask.js

import * as smask from "./smask.js";

Load the jQuery UI library (sortable widget) if you need the sortable functionality

Automatically format telephone numbers in a tel input field

input id="tel" name="tel" type="tel" inputmode="numeric" autocomplete="tel" placeholder="(00) 00000-0000" data-mask="(dd) ddddd-dddd" required />
// or
const phone = smask.mask("71984376521", "(dd) ddddd-dddd");
console.log("Cell phone: ", phone);
// or
smask.input(document.getElementById("phone"), "(dd) ddddd-dddd");

Unmask a numeric value

const postalCodeUnmasked = smask.unmask("12345-678", "ddddd-ddd");
console.log("Postal Code (unmasked): ", postalCodeUnmasked);

Format & unformat numbers and currency values:

const numberFormat = smask.number("1234.56", "en-US");
console.log("Number: ", numberFormat);
=> 1,234.56
const numberUnformat = smask.numberUnformat("1,234.56", "en-US");
console.log("Number: ", numberUnformat);
=> 1234.56
const currencyFormat = smask.currency("1234.56", "en-US", "USD");
console.log("Currency: ", currencyFormat);
=> $1,234.56
const currencyUnformat = smask.currencyUnformat("$1,234.56", "en-US", "USD");
console.log("Currency: ", currencyUnformat);
=> 1234.56

Mask input field

  // parameter: $row
  beforeAdd: null,
  beforeRemove: null, 
  beforeMove: null,
  beforeFormUpdateNames: null,
  beforeAll: null,
  afterAdd: null, 
  afterRemove: null,
  afterMove: null,
  afterFormUpdateNames: null,
  afterAll: null, 

Mask input field

// Numbers
smask.input(document.getElementById("phone"), ["ddd"]);
// Letters
smask.input(document.getElementById("letters"), ["aaa"]);
// Letters Uppercase
smask.input(document.getElementById("lettersUpper"), ["AAA"]);
// Alphanumeric
smask.input(document.getElementById("alphanum"), ["www"]);
// Alphanumeric Uppercase
smask.input(document.getElementById("alphanumUpper"), ["WWW"]);
// Date
smask.input(document.getElementById("date"), ["date"]);
// Price
smask.input(document.getElementById("price"), ["price"]);
// Single pattern
smask.input(document.getElementById("phone"), ["(dd) ddddd-dddd"]);
// Multiple patterns
smask.input(document.getElementById("phoneOrCellphone"), ["(dd) dddd-dddd", "(dd) ddddd-dddd"]);


Next: Trending Competitive Research Tools

also view other related posts,