Skip to content

Instantly share code, notes, and snippets.

@Southern
Last active October 11, 2015 06:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Southern/3815845 to your computer and use it in GitHub Desktop.
Save Southern/3815845 to your computer and use it in GitHub Desktop.
Phone Number Validator
// Remap `exports` to `window` if `exports` doesn't exist.
if (!exports) var exports = window;
// Regex to match numbers to.
var REGEX = /^\(?(?=\d{3})(\d{3})[).\-\s]*(\d{3})[.\-\s]*(\d{4})$/;
String.prototype.replace = (function(orig) {
return function(replace, replacement) {
// Allow arrays to be used.
if (replace instanceof Array) {
var out = this.toString();
replace.forEach(function(replace, id) {
if (~[ 'string', 'number' ].indexOf(typeof replacement))
out = out.replace(replace, replacement.toString());
else
out = out.replace(replace, replacement[id] && replacement[id].toString() || undefined);
});
return out;
}
return orig.apply(this, arguments);
};
})(String.prototype.replace);
function convertAlpha(number) {
return number.toString().replace([
/[a-c]/ig,
/[d-f]/ig,
/[g-i]/ig,
/[j-l]/ig,
/[m-o]/ig,
/[p-s]/ig,
/[t-v]/ig,
/[w-z]/ig
], [ 2, 3, 4, 5, 6, 7, 8, 9 ]);
}
exports.PhoneNumber = function(number, alpha) {
var regex = REGEX;
if (alpha) regex = regex.source.replace(/\\d/g, '[\\d\\w]');
var match = number.match(regex);
if (match) {
return {
full: convertAlpha(match.slice(1, 4).join('')),
area: convertAlpha(match[1]),
exchange: convertAlpha(match[2]),
number: convertAlpha(match[3]),
input: {
full: match.slice(1, 4).join(''),
area: match[1],
exchange: match[2],
number: match[3]
}
};
}
return match;
};
console.log(exports.PhoneNumber('1234567890'));
console.log(exports.PhoneNumber('ABCDEFGHIJ'));
console.log(exports.PhoneNumber('ABCDEFGHIJ', true));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment