Mark
Mark

Reputation: 187

How to create JavaScript Regular Expressions for the validation of International telephone numbers with extensions

I'm trying to match international phone numbers with extensions such as: +44 (123) 123 4567 ext. 123 and telephone numbers such as: +44 (123) 123 4567. When I type the extension it returns an invalid phone number. I also want to match US telephone numbers such as (212) 555-1212 and other telephone numbers, for example, +44 20 7893 4567. I am expecting user input using a prompt. My code is as follows:

function isValidTelephoneNumber(telephoneNumber){
    var telRegExp = /^(\+\d{1,3} ?)?(\(\d{1,5}\)|\d{1,5}) ?\d{3,4} ?\d{0,7}( (x|xtn|ext|extn|pax|pbx|extension)?\.? ?\d{2-5})?$/i;
    return telRegExp.test(telephoneNumber);
}

var phoneNumber = prompt("Please enter a phone number.", "");

if (isValidTelephoneNumber(phoneNumber)){
    alert("Valid Phone Number");
} else {
    alert("Invalid Phone Number");
}

Upvotes: 2

Views: 93

Answers (1)

ChaosPandion
ChaosPandion

Reputation: 78282

The last section you have a syntax error ?\d{2-5} should be ?\d{2,5} I also recommend using \s+ for your white space.

Upvotes: 1

Related Questions