Blog>
Snippets

Input Masking for Form Fields

Illustrate how to implement input masking for specific form fields like phone numbers or dates, ensuring that user input conforms to a required format.
// Listen for input on the phone number field
const phoneInput = document.querySelector('#phone-input');
phoneInput.addEventListener('input', handlePhoneInput);

// Format the phone number as the user types
function handlePhoneInput(event) {
  var input = event.target.value;
  input = input.replace(/\D/g,''); // Remove all non-numeric characters
  var formattedInput = '';

  // Apply the masking (for US phone numbers)
  if(input.length > 0) formattedInput += '(' + input.substring(0,3);
  if(input.length >= 4) formattedInput += ') ' + input.substring(3,6);
  if(input.length >= 7) formattedInput += '-' + input.substring(6,10);

  // Update the input field with the formatted value
  event.target.value = formattedInput;
}
This code listens for real-time input on a phone number field, and formats it as a US phone number with parentheses and dashes as the user types.
// Listen for input on the date field
const dateInput = document.querySelector('#date-input');
dateInput.addEventListener('input', handleDateInput);

// Format the date as the user types
function handleDateInput(event) {
  var input = event.target.value;
  input = input.replace(/\D/g,''); // Remove all non-numeric characters
  var formattedInput = '';

  // Apply the masking (for MM/DD/YYYY format)
  if(input.length > 0) formattedInput += input.substring(0,2);
  if(input.length >= 3) formattedInput += '/' + input.substring(2,4);
  if(input.length >= 5) formattedInput += '/' + input.substring(4,8);

  // Update the input field with the formatted value
  event.target.value = formattedInput;
}
This code listens for real-time input on a date field, and formats it as MM/DD/YYYY while the user types, ensuring separators are inserted in the correct positions.