public
Last active

Phone Number Validator

  • Download Gist
phonenumber.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62
// 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));

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.