Create a user friendly input mask and validation using JavaScript smask plugin

Author: marcelo-ribeiro
Official Page: Go to website
Last Update: June 26, 2021
License: MIT


You must be looking for a input mask plugin in JavaScript, that can help you in creating form validation in your project then, smask is good option, it helps formatting and validation input values such as phone numbers, price and quantity etc.

How can I use it?

Step 1: First, you will need to import the smask.js in a file like index.js.

import {mask, maskInput, unmask, prepareMaskInputs, currency, numberFormat} from "./smask.js"

Step 2: Create your input fields like this.

For cellphone:

<input class="field--text__input" id="tel" name="tel" type="tel" inputmode="numeric" autocomplete="tel" placeholder="(00) 00000-0000" data-mask="['(dd) dddd-dddd', '(dd) ddddd-dddd']" required>

Birth date:

<input class="field--text__input" id="date" name="date" type="tel" inputmode="numeric" placeholder="00/00/0000" data-mask="['dd/dd/dddd']" required>


<input class="field--text__input" id="price" name="price" type="tel" inputmode="numeric" required>

Step 3: Open your index.js and add the formatting and validation.

const phone = mask("71987654321", "(dd) ddddd-dddd");
console.log("Cell phone: ", phone);

Birth Date:
const date = mask("12345678", "dd/dd/dddd");
console.log("Date: ", date);

const currencyFormat = currency(1234.56);
maskInput("#price", ["currency"]);
// Setting price placeholder
document.getElementById("price").setAttribute("placeholder", currency(0));