Skip to content

Instantly share code, notes, and snippets.

@parisminton
Created July 26, 2016 17:48
Show Gist options
  • Save parisminton/5642b3f9b8bdf0800f6cb3c84875b4d5 to your computer and use it in GitHub Desktop.
Save parisminton/5642b3f9b8bdf0800f6cb3c84875b4d5 to your computer and use it in GitHub Desktop.
Front-end validation and formatting help for a phone number input. Relying on keycodes was problematic on Android.
function handlePhoneInput (evt) {
var inpt = evt.target,
op;
if (inpt.value.length > prev_inpt.length) {
op = 'typed';
}
else if (inpt.value.length < prev_inpt.length) {
op = 'deleted';
}
else {
op = 'parked';
}
function hyphenate (str) {
// add dash on initial type
if ((str.length === 3 || str.length === 7 )
&& op === 'typed') {
inpt.value = str += '-';
}
// remove dash or add it after an auto-removal
if ((str.length === 4 || str.length === 8)) {
if (str.charAt(str.length - 1) === '-'
&& op === 'deleted') {
inpt.value = str.substring(0, (str.length - 1));
}
else if (str.charAt(str.length -1) != '-') {
inpt.value = str.substring(0, (str.length - 1)) + '-' + str.charAt(str.length - 1);
}
}
} // end hyphenate
function clean (str) {
inpt.value = str.replace(/[^\d\-]/g, '');
if (str.length > 12) {
inpt.value = str.substring(0, 12);
}
} // end clean
hyphenate(inpt.value);
clean(inpt.value);
prev_inpt = inpt.value;
} // end handlePhoneInput
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment