How to Create Input Masks with JavaScript

Input masks help users enter data in a consistent format by automatically formatting it while typing. This is very useful for fields like phone number, date, or ZIP code.

In this tutorial, you’ll learn how to create real-time input masks using pure JavaScript, following the U.S. formatting standard.


👁️ Preview


🧱 Step 1: HTML Structure

We’ll create a simple form with common fields:

<form>
  <label>Phone Number (US):</label><br />
  <input type="text" id="phone" placeholder="(123) 456-7890" /><br /><br />

  <label>Date (MM/DD/YYYY):</label><br />
  <input type="text" id="date" placeholder="MM/DD/YYYY" /><br /><br />

  <label>ZIP Code:</label><br />
  <input type="text" id="zip" placeholder="12345" /><br /><br />

  <label>SSN:</label><br />
  <input type="text" id="ssn" placeholder="123-45-6789" />
</form>

⚙️ Step 2: JavaScript for Real-Time Masking

function maskInput(input, pattern) {
  input.addEventListener("input", function () {
    let i = 0;
    const value = input.value.replace(/\D/g, "");
    const formatted = pattern.replace(/#/g, _ => value[i++] || "");
    input.value = formatted;
  });
}

// Apply masks
maskInput(document.getElementById("phone"), "(###) ###-####");
maskInput(document.getElementById("date"), "##/##/####");
maskInput(document.getElementById("zip"), "#####");
maskInput(document.getElementById("ssn"), "###-##-####");

✅ Explanation

  • The maskInput function:
    • Removes non-numeric characters using .replace(/\D/g, '')
    • Uses a pattern string like "(###) ###-####" to apply the formatting
    • Replaces each # in the pattern with the user’s digits as they type

This allows you to easily apply different masks to any input field.


🎨 Optional CSS Styling

input {
  padding: 10px;
  font-size: 1rem;
  width: 250px;
  margin-bottom: 1rem;
}

You can adjust styles to match your UI.


🧠 Why Use Input Masks?

  • Avoids data entry errors
  • Improves user experience
  • Helps with form validation and formatting

✅ Final Result

You’ve created multiple masked inputs that:

  • Format data in real time
  • Follow the U.S. pattern standard
  • Use only HTML + vanilla JavaScript
  • Are reusable for other fields

Leave a Comment