Live Phone Number Formatting

by Travis Almand

HTML

<input type="tel" inputmode="tel" pattern="(\([0-9]{3}\)) ([0-9]{3})-([0-9]{4})" />

CSS

input:invalid {
  border: 1px solid red;
}

JavaScript

const input = document.querySelector('input');

input.addEventListener('keydown', function (e) {
	// strip non-numeric characters from input string
	const phone = e.target.value.replace(/\D/g, '');
  
  // allow backspace
  if (e.key === 'Backspace') {
    return true;
  }
  
  // if non-numeric character attempted, prevent it
  // lock down length of value
  if (/[^0-9]/.test(e.key) || phone.length === 10) {
    e.preventDefault();
  }
});

input.addEventListener('keyup', function (e) {
	// strip non-numeric characters from input string
	const phone = e.target.value.replace(/\D/g, '');
  
  // collect each section of the phone number
  const first = phone.substring(0,3);
  const second = phone.substring(3,6);
  const third = phone.substring(6,10);
  
  // change display based on length of value
  if (phone.length > 6) {
  	e.target.value = `(${first}) ${second}-${third}`;
  } else if (phone.length > 3) {
  	e.target.value = `(${first}) ${second}`;
  } else if (phone.length > 0) {
  	e.target.value = `(${first}`;
  }
});