Skip to content

Instantly share code, notes, and snippets.

@pseudosavant
Last active August 29, 2015 14:18
Show Gist options
  • Save pseudosavant/a39157521dc67bbbb6d7 to your computer and use it in GitHub Desktop.
Save pseudosavant/a39157521dc67bbbb6d7 to your computer and use it in GitHub Desktop.
Regex for validating/finding U.S. phone numbers
// Regex for validating/finding U.S. phone numbers
// http://jsbin.com/hupupopiya/
// http://regexr.com/3anot
var phoneRe = /^1?[\W\D]{0,2}([2-9]\d{2})[\W\D]{0,2}([2-9](?:1[02-9]|[02-9]\d))[\W\D]?(\d{4})$/;
var validNumbers = [
'760-807-8178',
'17608078178',
'(760)807-8178',
'1(760)807-8178',
'1-760-807-8178',
'911-867-5309',
'760-912-8763',
'913-867-5309',
'1-(800)-555-2468',
'1-(760)-807-8178',
];
var invalidNumbers = [
'760-911-8763'
];
function isValidPhoneNumber(s) {
return phoneRe.test(s);
}
validNumbers.forEach(function(v){
var valid = (isValidPhoneNumber(v) ? 'valid' : 'invalid');
console.log(v + ':' + valid);
});
// "760-807-8178:valid"
// "17608078178:valid"
// "(760)807-8178:valid"
// "1(760)807-8178:valid"
// "1-760-807-8178:valid"
// "911-867-5309:valid"
// "760-912-8763:valid"
// "913-867-5309:valid"
// "1-(800)-555-2468:valid"
// "1-(760)-807-8178:valid"
invalidNumbers.forEach(function(v){
var valid = (isValidPhoneNumber(v) ? 'valid' : 'invalid');
console.log(v + ':' + valid);
});
// "760-911-8763:invalid"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment