Super Robust Phone Number Validation in Javascript
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

I've seen a lot of examples of phone number validation in Javascript but I need some code that validates the value of a text input field super robust-ly.

I need it to account for irregular spaces, parentheses and other symbols commonly used in phone numbers.

I want it to accept the following as valid formats, for example:
+1 (555) 555-5555
(555) 555-5555
(555) 555555 5

...and so on. Any format you can think of. I don't know all the valid formats, but I need a function that uses a regex or something so that I can validate but not require the user adhere to a certain format. The code must produce a valid number acceptable by Twilio.

awarded to alex

Crowdsource coding tasks.

3 Solutions

You can't use PhoneFormat.js? is really solid and built using Google's libphonenumber library.

@datamosh, if you provide a full working example, there's a good chance you'll win the bounty!
bevan 9 years ago

PhoneFormat.js examples:

Only US:

With country select:

Winning solution

I am unsure as what exactly you are looking for, but I belive these functions below might work. All you have to do is to run the string through the function. The first function numbersOnly will take any string and remove all non-number characters. The second function will do the same but also will only accept the first 15 characters (because the E.164 recommendation for phone numbers only allows 15 characters). The third function does what the second function does but also adds the + infront of the numbers.

function numbersOnly(string) { 
    return(string.replace(/[^0-9]/g, ''));

// 1a234d5-6f7g8(901[]2)3/456 => 1234567890123456

function numberLength(string) {
    return(string.replace(/[^0-9]/g, '').substring(0,15));

// 1a234d5-6f7g8(901[]2)3/456 => 123456789012345

function numberPlus(string) {
    return('+'+string.replace(/[^0-9]/g, '').substring(0,15));

// 1a234d5-6f7g8(901[]2)3/456 => +123456789012345

function formatNumberUS(string) {
    var string = string.replace(/[^0-9]/g, '').substring(0,10);
    var first3 = string.substring(0,3);
    var next3 = string.substring(3,6);
    var next4 = string.substring(6,10);
    return("+1("+first3+") "+next3+"-"+next4);

//9\[[a0[]]a0+as84dasd,,<>61sdf6as41 => +1(900) 846-1641
View Timeline