Last active
January 2, 2016 15:39
-
-
Save astromac/8325373 to your computer and use it in GitHub Desktop.
7 and 10 digit US phone number validation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function validatePhoneNumber(phonenumber) { | |
| var pattern = /^(?:(?:\(\s*([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9])\s*\)|([2-9]1[02-9]|[2-9][02-8]1|[2-9][02-8][02-9]))\s*(?:[.-]\s*)?)?([2-9]1[02-9]|[2-9][02-9]1|[2-9][02-9]{2})\s*(?:[.-]\s*)?([0-9]{4})(?:\s*(?:\s+|#|x\.?|ext\.?|extension)\s*(\d+))?$/i; | |
| var matches = []; | |
| var validnumber = []; | |
| validnumber.unformatted = ''; | |
| if (phonenumber.length > 0) { | |
| if (pattern.test(phonenumber)) { | |
| matches = phonenumber.match(pattern); | |
| // split phone number input into phone number format array | |
| for (var i = matches.length - 1; i >= 0; i--) { | |
| if (matches[i] !== undefined && i !== 0) { | |
| switch (i) { | |
| case 5: | |
| validnumber.extension = matches[i]; | |
| break; | |
| case 4: | |
| validnumber.suffix = matches[i]; | |
| break; | |
| case 3: | |
| validnumber.prefix = matches[i]; | |
| break; | |
| case 2: | |
| validnumber.areacode = matches[i]; | |
| break; | |
| case 1: | |
| validnumber.areacode = matches[i]; | |
| } | |
| } | |
| } | |
| if (validnumber.areacode) { | |
| validnumber.unformatted = validnumber.areacode; | |
| } | |
| if (validnumber.prefix) { | |
| validnumber.unformatted += validnumber.prefix; | |
| } | |
| if (validnumber.suffix) { | |
| validnumber.unformatted += validnumber.suffix; | |
| } | |
| if (validnumber.extension) { | |
| validnumber.unformatted += validnumber.extension; | |
| } | |
| return validnumber; | |
| } else { | |
| return false; // invalid phone number | |
| } | |
| } else { | |
| return false; // nothing passed | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment