Skip to content

Instantly share code, notes, and snippets.

@anderfernandes
Created March 7, 2017 21:46
Show Gist options
  • Save anderfernandes/d441a8e81d5fd39d6d6c34e5f12b5e18 to your computer and use it in GitHub Desktop.
Save anderfernandes/d441a8e81d5fd39d6d6c34e5f12b5e18 to your computer and use it in GitHub Desktop.
Phone Input Masking
// This function masks a phone number in an input field of id 'phone', mask is (999) 999-9999
document.getElementById('phone').addEventListener('input', function (e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
e.target.value = !x[2] ? x[1] : '(' + x[1] + ') ' + x[2] + (x[3] ? '-' + x[3] : '');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment