Skip to content

Instantly share code, notes, and snippets.

@clandestine8
Created April 4, 2022 19:53
Show Gist options
  • Save clandestine8/819afed6976457ed98f5d208461c5cc8 to your computer and use it in GitHub Desktop.
Save clandestine8/819afed6976457ed98f5d208461c5cc8 to your computer and use it in GitHub Desktop.
Auto Format North American Phone Numbers in HTML Forms using Vanilla JS
document.addEventListener('DOMContentLoaded', function() {
let tels = document.querySelectorAll('input[type=tel]');
tels.forEach(function (tel) {
if (tel) {
tel.addEventListener('change', function () {
let inputField = this
inputField.value = formatPhoneNumber(inputField.value);
});
tel.addEventListener('keyup', function () {
let inputField = this
inputField.value = formatPhoneNumber(inputField.value);
});
}
})
}, false);
window.formatPhoneNumber = function (value) {
if (!value) return value;
const phoneNumber = value.replace(/[^\d]/g, '');
const phoneNumberLength = phoneNumber.length;
if (phoneNumberLength < 4) return phoneNumber;
if (phoneNumberLength < 7) {
return `(${phoneNumber.slice(0, 3)}) ${phoneNumber.slice(3)}`;
}
return `(${phoneNumber.slice(0, 3)}) ${phoneNumber.slice(
3,
6
)}-${phoneNumber.slice(6, 10)}`;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment