By Nicholas Trandem


2008-09-23 20:13:42 8 Comments

I'm trying to put together a comprehensive regex to validate phone numbers. Ideally it would handle international formats, but it must handle US formats, including the following:

  • 1-234-567-8901
  • 1-234-567-8901 x1234
  • 1-234-567-8901 ext1234
  • 1 (234) 567-8901
  • 1.234.567.8901
  • 1/234/567/8901
  • 12345678901

I'll answer with my current attempt, but I'm hoping somebody has something better and/or more elegant.

30 comments

@SIM 2018-04-17 21:08:10

As there is no language tag with this post, I'm gonna give a regex solution used within python.

The expression itself:

1[\s./-]?\(?[\d]+\)?[\s./-]?[\d]+[-/.]?[\d]+\s?[\d]+

When used within python:

import re

phonelist ="1-234-567-8901,1-234-567-8901 1234,1-234-567-8901 1234,1 (234) 567-8901,1.234.567.8901,1/234/567/8901,12345678901"

phonenumber = '\n'.join([phone for phone in re.findall(r'1[\s./-]?\(?[\d]+\)?[\s./-]?[\d]+[-/.]?[\d]+\s?[\d]+' ,phonelist)])
print(phonenumber)

Output:

1-234-567-8901
1-234-567-8901 1234
1-234-567-8901 1234
1 (234) 567-8901
1.234.567.8901
1/234/567/8901
12345678901

@Shylendra Madda 2018-03-20 06:46:26

Try this (It is for Indian mobile number validation):

if (!phoneNumber.matches("^[6-9]\\d{9}$")) {
  return false;
} else {
  return true;
}

@vivek_23 2019-01-25 16:30:50

Why not just return the output of matches?

@Gautam Sharma 2018-03-12 08:52:58

Note It takes as an input a US mobile number in any format and optionally accepts a second parameter - set true if you want the output mobile number formatted to look pretty. If the number provided is not a mobile number, it simple returns false. If a mobile number IS detected, it returns the entire sanitized number instead of true.

    function isValidMobile(num,format) {
        if (!format) format=false
        var m1 = /^(\W|^)[(]{0,1}\d{3}[)]{0,1}[.]{0,1}[\s-]{0,1}\d{3}[\s-]{0,1}[\s.]{0,1}\d{4}(\W|$)/
        if(!m1.test(num)) {
           return false
        }
        num = num.replace(/ /g,'').replace(/\./g,'').replace(/-/g,'').replace(/\(/g,'').replace(/\)/g,'').replace(/\[/g,'').replace(/\]/g,'').replace(/\+/g,'').replace(/\~/g,'').replace(/\{/g,'').replace(/\*/g,'').replace(/\}/g,'')
        if ((num.length < 10) || (num.length > 11) || (num.substring(0,1)=='0') || (num.substring(1,1)=='0') || ((num.length==10)&&(num.substring(0,1)=='1'))||((num.length==11)&&(num.substring(0,1)!='1'))) return false;
        num = (num.length == 11) ? num : ('1' + num);   
        if ((num.length == 11) && (num.substring(0,1) == "1")) {
            if (format===true) {
               return '(' + num.substr(1,3) + ') ' + num.substr(4,3) + '-' + num.substr(7,4)
            } else {
               return num
            }
        } else {
            return false;
        }
    }

@Halfwarr 2013-03-26 18:13:37

I would also suggest looking at the "libphonenumber" Google Library. I know it is not regex but it does exactly what you want.

For example, it will recognize that:

15555555555

is a possible number but not a valid number. It also supports countries outside the US.

Highlights of functionality:

  • Parsing/formatting/validating phone numbers for all countries/regions of the world.
  • getNumberType - gets the type of the number based on the number itself; able to distinguish Fixed-line, Mobile, Toll-free, Premium Rate, Shared Cost, VoIP and Personal Numbers (whenever feasible).
  • isNumberMatch - gets a confidence level on whether two numbers could be the same.
  • getExampleNumber/getExampleNumberByType - provides valid example numbers for all countries/regions, with the option of specifying which type of example phone number is needed.
  • isPossibleNumber - quickly guessing whether a number is a possible phonenumber by using only the length information, much faster than a full validation.
  • isValidNumber - full validation of a phone number for a region using length and prefix information.
  • AsYouTypeFormatter - formats phone numbers on-the-fly when users enter each digit.
  • findNumbers - finds numbers in text input.
  • PhoneNumberOfflineGeocoder - provides geographical information related to a phone number.

Examples

The biggest problem with phone number validation is it is very culturally dependant.

  • America
    • (408) 974–2042 is a valid US number
    • (999) 974–2042 is not a valid US number
  • Australia
    • 0404 999 999 is a valid Australian number
    • (02) 9999 9999 is also a valid Australian number
    • (09) 9999 9999 is not a valid Australian number

A regular expression is fine for checking the format of a phone number, but it's not really going to be able to check the validity of a phone number.

I would suggest skipping a simple regular expression to test your phone number against, and using a library such as Google's libphonenumber (link to GitHub project).

Introducing libphonenumber!

Using one of your more complex examples, 1-234-567-8901 x1234, you get the following data out of libphonenumber (link to online demo):

Validation Results

Result from isPossibleNumber()  true
Result from isValidNumber()     true

Formatting Results:

E164 format                    +12345678901
Original format                (234) 567-8901 ext. 123
National format                (234) 567-8901 ext. 123
International format           +1 234-567-8901 ext. 123
Out-of-country format from US  1 (234) 567-8901 ext. 123
Out-of-country format from CH  00 1 234-567-8901 ext. 123

So not only do you learn if the phone number is valid (which it is), but you also get consistent phone number formatting in your locale.

As a bonus, libphonenumber has a number of datasets to check the validity of phone numbers, as well, so checking a number such as +61299999999 (the international version of (02) 9999 9999) returns as a valid number with formatting:

Validation Results

Result from isPossibleNumber()  true
Result from isValidNumber()     true

Formatting Results

E164 format                    +61299999999
Original format                61 2 9999 9999
National format                (02) 9999 9999
International format           +61 2 9999 9999
Out-of-country format from US  011 61 2 9999 9999
Out-of-country format from CH  00 61 2 9999 9999

libphonenumber also gives you many additional benefits, such as grabbing the location that the phone number is detected as being, and also getting the time zone information from the phone number:

PhoneNumberOfflineGeocoder Results
Location        Australia

PhoneNumberToTimeZonesMapper Results
Time zone(s)    [Australia/Sydney]

But the invalid Australian phone number ((09) 9999 9999) returns that it is not a valid phone number.

Validation Results

Result from isPossibleNumber()  true
Result from isValidNumber()     false

Google's version has code for Java and Javascript, but people have also implemented libraries for other languages that use the Google i18n phone number dataset:

Unless you are certain that you are always going to be accepting numbers from one locale, and they are always going to be in one format, I would heavily suggest not writing your own code for this, and using libphonenumber for validating and displaying phone numbers.

@michaelhanson 2016-09-12 18:59:40

Noting that there is now also Go port at: github.com/ttacon/libphonenumber

@BugHunterUK 2016-11-28 23:22:54

When checking if it's a possible number don't you need to specify a country code? I'm using the PHP version and if I enter a British number like (replace 0's with real numbers) 07700000000 I get Missing or invalid default region. error. But if I specify the country code it will pass.

@sijo vijayan 2017-07-22 08:26:27

FYI : This library does not support some countries, phpinterviewquestions.co.in/blog/ionic/…

@IMSoP 2018-03-22 16:56:31

@BugHunterUK (and anyone who comes across this question and wonders the same) when parsing a number, you can specify the expected region, and the library will look for non-international numbers in that region. If you don't specify, it will reject anything not in a valid international format.

@user230910 2018-10-09 02:09:12

Does it come with free tracking and tracing users on sites / programs that use it :-p ?

@Ismael Miguel 2014-01-07 12:30:34

/^(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\\/]?){0,})(?:[\-\.\ \\\/]?(?:#|ext\.?|extension|x)[\-\.\ \\\/]?(\d+))?$/i

This matches:

 - (+351) 282 43 50 50
 - 90191919908
 - 555-8909
 - 001 6867684
 - 001 6867684x1
 - 1 (234) 567-8901
 - 1-234-567-8901 x1234
 - 1-234-567-8901 ext1234
 - 1-234 567.89/01 ext.1234
 - 1(234)5678901x1234
 - (123)8575973
 - (0055)(123)8575973

On $n, it saves:

  1. Country indicator
  2. Phone number
  3. Extension

You can test it on https://www.regexpal.com/?fam=99127

@Ismael Miguel 2014-03-07 19:56:19

In which engine? In Javascript and PHP works perfectly fine.

@bafromca 2014-03-07 20:10:01

This was the most comprehensive regex I've seen. It's easy to get around until you remove ^ and $ or else I'm able to get around it using [111] [111] [1111] or 111--111--1111 and the like. (sorry, deleted my last comment)

@Ismael Miguel 2014-03-07 20:13:03

Can you please re-phrase? I can't understand this: "It's easy to get arround until you remove ^ and $ or else I'm able to get around it using [111] [111] [1111]". Does it mean that it validates '[111] [111] [1111]' when you take the ^ and the $?

@bafromca 2014-03-07 20:15:51

I got around your regex using [111] [111] [1111] and 111--111--1111 until I removed ^ and $ from the regex.

@Ismael Miguel 2014-03-07 20:18:45

As I asked before, which engine are you using? 111-111-1111 validates perfectly (syntactically, the second one is valid) while [111] [111] [1111] doesn't validate (as expected)

@bafromca 2014-03-07 20:21:04

gethifi.com/tools/regex and I meant 111--111--1111 as mentioned above.

@Ismael Miguel 2014-03-07 20:25:52

111--111--1111 is invalid: i62.tinypic.com/2rnhr7k.png (perfectly fine) and [111] [111] [1111] is also invalid: i58.tinypic.com/9ru64y.png (as expected)

@bafromca 2014-03-07 21:57:49

@Matt Cashatt 2014-07-18 16:53:17

^^^This is a great example of why comment threads should NOT go to chat. I am very interested in how this conversation turned out and need to know if this ReGex is sturdy enough to use in my app. Unfortunately, the chat conversation is now gone.

@Ismael Miguel 2014-07-19 18:09:47

To be honest, i didnt went to chat. After asking multiple times for explainations, i was left with no info. You can always try it yourself with all kind of numbers you find online, in multiple formats. One thing i tried with this one is to use multiple phone numbers, but it doesnt work that well if they have spaces around. And i have to find a solution to count the amount of digits and enforce a specific amount.

@Kousha 2017-02-17 00:29:59

How do I make this so it can extract the number from a string, anywhere that the phone number may be?

@Ismael Miguel 2017-02-17 00:31:11

@Kousha Remove the ^ and the $, and it should work with lots of false positives.

@Kousha 2017-02-17 00:41:52

@IsmaelMiguel that doesn't work: ideone.com/FjZ4fq

@Ismael Miguel 2017-02-17 01:18:33

@Kousha That's expected. You're trying to make a Javascript RegExp work on PHP with PCRE. You need to slightly re-write it. Which is outside the scope of this question. Using regex101.com, pasting the regex there and going to "tools" -> "code generator", you get this: /(?:(?:\(?(?:00|\+)([1-4]\d\d|[1-9]\d?)\)?)?[\-\.\ \\\\\/]?)?((?:\(?\d{1,}\)?[\-\.\ \\\\\/]?){0,})(?:[\-\.\ \\\\\/]?(?:#|ext\.?|extension|x)[\-\.\ \\\\\/]?(\d+))?/i. And this one works.

@Sai prateek 2017-02-02 12:41:57

Find String regex = "^\\+(?:[0-9] ?){6,14}[0-9]$";

helpful for international numbers.

@scunliffe 2008-09-23 20:35:51

Better option... just strip all non-digit characters on input (except 'x' and leading '+' signs), taking care because of the British tendency to write numbers in the non-standard form +44 (0) ... when asked to use the international prefix (in that specific case, you should discard the (0) entirely).

Then, you end up with values like:

 12345678901
 12345678901x1234
 345678901x1234
 12344678901
 12345678901
 12345678901
 12345678901
 +4112345678
 +441234567890

Then when you display, reformat to your hearts content. e.g.

  1 (234) 567-8901
  1 (234) 567-8901 x1234

@Daniel Earwicker 2009-07-21 12:13:05

The formatting code is going to be a waste of time if the numbers are allowed to come from outside the US.

@scunliffe 2009-07-21 13:36:28

@Earwicker - agreed the formatting (if dealing with international #'s) should be smart enough to handle various formats... e.g. (0123) 456 7890 or +1 234 567-89-01. Depending how complex you want to get it should be something that can be figured out based on the number of digits and what the first few digits are.

@Hugh Jeffner 2010-07-29 13:40:41

This is good and all, but it doesn't validate what was entered was actually a phone number. For example, what if the user doesn't enter the requisite 10 digits? This should be combined with good regex validation.

@Joel McBeth 2010-12-06 19:51:06

string.replace("[^\d+!x]", "")

@Danilo Bargen 2011-01-28 22:09:13

jcmcbeth, why the !x part? This seems to suffice: [^\d+] rubular.com/r/aj32fRSSGK

@cdeszaq 2011-02-28 16:53:44

@danilo - The !x is there to keep any "x" character from getting stripped so that extensions can be separated out.

@PlexQ 2012-03-30 17:12:12

Considering the question was about validation - this is a really really bad answer.

@scunliffe 2012-03-30 20:19:04

@PlexQ I disagree. The original problem is trying to handle phone number validation because it was trying to handle all the possible formatting options. Rather than try to solve all that, take the input and "pre-strip" it of all formatting fluff until you have just the "number". Doing this solves 2 problems - testing the result is now easy and you can now ensure that values rendered back out for display can all be formatted consistently. The first comment on this answer about the "Complicator's Gloves" is a good read... sometimes the answer to a problem is to approach it differently.

@Dan Nissenbaum 2012-04-26 21:18:16

For others who may be using the above [^\d+!x] - the exclamation point is unnecessary. Just use [^\d+x]. See stackoverflow.com/questions/10340336/….

@scunliffe 2012-07-04 19:21:27

@Raymond you can use $justDigitsOrPlusOrX = preg_replace("/[^\d+x]/", "", $phoneNum); to strip away all the chars you don't need... then test the remaining (if needed)

@Swanand 2013-02-15 06:40:23

This works nicely, except in case of numbers like 1-800-CALL-NOW?

@scunliffe 2013-02-15 14:32:02

@Swanand I suppose in those scenarios if that's what you really wanted you could enable a smart translation that would convert the letters to their matching numbers... but I think that's a very special corner case compared to what most folks are after. ;-)

@Albert Bori 2013-05-13 20:37:29

Improvement on Regex above: /[^\d+x]|x(?=[^x]*x)/gi Prevents multiple x's (uses the last x in the string)

@Kehlan Krumme 2013-08-09 17:53:50

This is nice, but it does not answer the posed question that explicitly requests a RegEx solution.

@scunliffe 2013-08-27 21:10:00

@nashwan did you read the article linked in the first comment added by Nicholas Trandem the Original Question Poster? Sometimes (as you can see how the community has voted) even though there is a solution to use a 261 character regex that handles a bunch of scenarios... trying to attack the problem in a different manner is actually the answer you want. Note Dave Kirby's answer also suggests not using a strict regex... also gaining (ATM 79 upvotes)

@ekillaby 2013-10-17 02:12:42

@Swanand It's cute when people spell things out in the letter mappings that are on most phone keypads, but it's not encouraged in the standards. tools.ietf.org/html/rfc3966#section-5.1.2

@Jack Holt 2013-11-26 16:39:26

You can't just allow anything and then strip out what you don't want if you plan to format later. You need something you can format later.

@scunliffe 2013-11-26 19:43:44

I should clarify that I would "store" the clean value, and only "decorate" it as needed for display later on.

@alastair 2014-04-01 11:19:42

You do need to be careful when presented with an number starting +44 (0) as well. This is a very common format in the UK, and you probably want to map it to +44 (i.e. remove the (0)).

@uliwitness 2014-04-01 13:03:43

Yeah, validating or formatting phone numbers is not a good idea. The following are all valid German phone numbers: +49 (0) 89 12345, +49 (0)6221 1234. If you're in Germany, you'd dial those as 089 12345 or 06221 1234, but from e.g. Switzerland it'd be 0049 89 12345 or 0049 6221 1234. So this is like the UK case, but our area codes don't have a fixed length. Unless you have a list, you can't format the numbers correctly.

@jlars62 2014-06-19 18:37:14

How the hell is this such a highly voted answer? This doesn't validate anything. What's worse is all the other phone number validation questions reference this one...

@totallyNotLizards 2014-06-26 15:41:04

@jlars62 it may not validate a phone number, but it offers an alternate solution that is more reliable than trying to divine whether a given phone number is valid - considering that the idea of valid differs significantly between countries. IMO it's a good solution, while I agree it doesn't validate it still solves the problem.

@Peyton 2014-07-04 17:36:24

@configurator Well, country dialing codes have the prefix property, so your example (4 (420) 778-457800) if 4 is the country code and 420 is an area/city code) could not be a real number, however your point that the "+" is important to designate whether the first number(s) are a country code stands -- maybe a better example would be

@JohnMerlino 2014-08-15 18:32:32

This works but adds a layer of complexity to the logic.

@John Shedletsky 2015-05-01 01:25:23

Does not use regular expressions. +1

@Ben 2015-09-08 09:31:59

See also : technet.microsoft.com/en-us/library/cc728034(v=ws.10).aspx If using TAPI to dial on windows this may help.

@Josh Habdas 2016-01-09 23:24:15

I created a public gist providing an ES6 function building on the regex @AlbertBori provided. Feedback welcomed.

@mwfearnley 2016-03-10 10:46:22

UK numbers (+44) should have 10 digits after the 0/+44. e.g. 01234 567 890

@Mark 2016-03-21 22:00:01

@mwfearnley Not all there are ones with 9 and 7 (also freephone ones with 9 and 7) en.wikipedia.org/wiki/Telephone_numbers_in_the_United_Kingdo‌​m and in living memory the length has changed

@mwfearnley 2016-03-22 22:06:11

I stand corrected.. I'm old enough to remember the change - I used to live in 0234 :)

@Jmons 2017-05-02 18:06:26

I muse: "because of the British tendency to write numbers in the non-standard form +44 (0)" If its a tendency of a lot of people, is this not a standard then? (and bloody annoying, even if I do it myself).

@Joe Johnston 2017-09-11 17:31:30

@fdsfdsfdsfds 2017-12-11 09:26:03

how could this be validated as the best answer honestly

@Leo Gurdian 2018-01-26 23:33:02

Not acceptable, what if you don't control the input ? it doesn't address the question.

@ell 2018-04-17 21:23:25

This is a great answer. It's showing that you should convert to an integer, then validate that (presumably using a simple algorithm). That part is implied, or at least seems obvious to me. Validating a phone number with a regex on the fly is insane. Besides... what is there to validate in the first place? That it's a real phone number? Why? If the user provides a bad phone number, that's their problem.

@Frank 2015-10-03 07:50:04

It's near to impossible to handle all sorts of international phone numbers using simple regex.

You'd be better off using a service like numverify.com, they're offering a free JSON API for international phone number validation, plus you'll get some useful details on country, location, carrier and line type with every request.

@Herobrine2Nether 2015-09-11 22:02:49

I found this to work quite well:

^\(*\+*[1-9]{0,3}\)*-*[1-9]{0,3}[-. /]*\(*[2-9]\d{2}\)*[-. /]*\d{3}[-. /]*\d{4} *e*x*t*\.* *\d{0,4}$

It works for these number formats:

1-234-567-8901
1-234-567-8901 x1234
1-234-567-8901 ext1234
1 (234) 567-8901
1.234.567.8901
1/234/567/8901
12345678901
1-234-567-8901 ext. 1234
(+351) 282 433 5050

Make sure to use global AND multiline flags to make sure.

Link: http://www.regexr.com/3bp4b

@Ben Clifford 2010-03-21 16:32:50

Note that stripping () characters does not work for a style of writing UK numbers that is common: +44 (0) 1234 567890 which means dial either the international number:
+441234567890
or in the UK dial 01234567890

@Artjom Kurapov 2010-02-04 09:52:21

I wrote simpliest (although i didn't need dot in it).

^([0-9\(\)\/\+ \-]*)$

As mentioned below, it checks only for characters, not its structure/order

@Brian Armstrong 2010-08-11 19:53:04

Didn't work for me.

@Steven Soroka 2013-03-28 14:47:26

this validates tons of numbers that are technically invalid. like, "-- +()()())())))". Learn to read regular expressions so you can understand what you're doing.

@happyhardik 2013-08-23 18:44:48

@StevenSoroka technically it may allow lot of invalid cases, but when we think about just helping the user out to avoid common mistakes with the simplest possible solution, this is the way to go :)

@Wasim A. 2013-09-16 08:13:53

this also matching white space, empty line

@dijipiji 2014-02-04 12:18:08

@HappyHardik. Indeed. Simple and powerful, for basic validation let the user type more than one dot, dash, bracket or plus.

@Derek 朕會功夫 2014-08-01 16:47:30

This is so incorrect.

@Stelios Voskos 2015-07-29 10:44:34

Just used it and it's wrong in many aspects. For example, a UK phone number may begin with +44, or a phone nuber may have (0) inside it. But this is not valid according to your regular expression. I would recommend @Ismael Miguel's answer. It works just fine and I would recommend you to revise your answer.

@bcherny 2015-06-30 05:31:25

/\b(\d{3}[^\d]{0,2}\d{3}[^\d]{0,2}\d{4})\b/

@Bob-ob 2011-08-09 10:36:50

For anyone interested in doing something similar with Irish mobile phone numbers, here's a straightforward way of accomplishing it:

http://ilovenicii.com/?p=87

PHP


<?php
$pattern = "/^(083|086|085|086|087)\d{7}$/";
$phone = "087343266";

if (preg_match($pattern,$phone)) echo "Match";
else echo "Not match";

There is also a JQuery solution on that link.

EDIT:

jQuery solution:

    $(function(){
    //original field values
    var field_values = {
            //id        :  value
            'url'       : 'url',
            'yourname'  : 'yourname',
            'email'     : 'email',
            'phone'     : 'phone'
    };

        var url =$("input#url").val();
        var yourname =$("input#yourname").val();
        var email =$("input#email").val();
        var phone =$("input#phone").val();


    //inputfocus
    $('input#url').inputfocus({ value: field_values['url'] });
    $('input#yourname').inputfocus({ value: field_values['yourname'] });
    $('input#email').inputfocus({ value: field_values['email'] }); 
    $('input#phone').inputfocus({ value: field_values['phone'] });



    //reset progress bar
    $('#progress').css('width','0');
    $('#progress_text').html('0% Complete');

    //first_step
    $('form').submit(function(){ return false; });
    $('#submit_first').click(function(){
        //remove classes
        $('#first_step input').removeClass('error').removeClass('valid');

        //ckeck if inputs aren't empty
        var fields = $('#first_step input[type=text]');
        var error = 0;
        fields.each(function(){
            var value = $(this).val();
            if( value.length<12 || value==field_values[$(this).attr('id')] ) {
                $(this).addClass('error');
                $(this).effect("shake", { times:3 }, 50);

                error++;
            } else {
                $(this).addClass('valid');
            }
        });        

        if(!error) {
            if( $('#password').val() != $('#cpassword').val() ) {
                    $('#first_step input[type=password]').each(function(){
                        $(this).removeClass('valid').addClass('error');
                        $(this).effect("shake", { times:3 }, 50);
                    });

                    return false;
            } else {   
                //update progress bar
                $('#progress_text').html('33% Complete');
                $('#progress').css('width','113px');

                //slide steps
                $('#first_step').slideUp();
                $('#second_step').slideDown();     
            }               
        } else return false;
    });

    //second section
    $('#submit_second').click(function(){
        //remove classes
        $('#second_step input').removeClass('error').removeClass('valid');

        var emailPattern = /^[a-zA-Z0-9._-][email protected][a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;  
        var fields = $('#second_step input[type=text]');
        var error = 0;
        fields.each(function(){
            var value = $(this).val();
            if( value.length<1 || value==field_values[$(this).attr('id')] || ( $(this).attr('id')=='email' && !emailPattern.test(value) ) ) {
                $(this).addClass('error');
                $(this).effect("shake", { times:3 }, 50);

                error++;
            } else {
                $(this).addClass('valid');
            }


        function validatePhone(phone) {
        var a = document.getElementById(phone).value;
        var filter = /^[0-9-+]+$/;
            if (filter.test(a)) {
                return true;
            }
            else {
                return false;
            }
        }

        $('#phone').blur(function(e) {
            if (validatePhone('txtPhone')) {
                $('#spnPhoneStatus').html('Valid');
                $('#spnPhoneStatus').css('color', 'green');
            }
            else {
                $('#spnPhoneStatus').html('Invalid');
            $('#spnPhoneStatus').css('color', 'red');
            }
        });

     });

        if(!error) {
                //update progress bar
                $('#progress_text').html('66% Complete');
                $('#progress').css('width','226px');

                //slide steps
                $('#second_step').slideUp();
                $('#fourth_step').slideDown();     
        } else return false;

    });


    $('#submit_second').click(function(){
        //update progress bar
        $('#progress_text').html('100% Complete');
        $('#progress').css('width','339px');

        //prepare the fourth step
        var fields = new Array(
            $('#url').val(),
            $('#yourname').val(),
            $('#email').val(),
            $('#phone').val()

        );
        var tr = $('#fourth_step tr');
        tr.each(function(){
            //alert( fields[$(this).index()] )
            $(this).children('td:nth-child(2)').html(fields[$(this).index()]);
        });

        //slide steps
        $('#third_step').slideUp();
        $('#fourth_step').slideDown();            
    });


    $('#submit_fourth').click(function(){

        url =$("input#url").val();
        yourname =$("input#yourname").val();
        email =$("input#email").val();
        phone =$("input#phone").val();

        //send information to server
        var dataString = 'url='+ url + '&yourname=' + yourname + '&email=' + email + '&phone=' + phone;  



        alert (dataString);//return false;  
            $.ajax({  
                type: "POST",  
                url: "http://clients.socialnetworkingsolutions.com/infobox/contact/",  
                data: "url="+url+"&yourname="+yourname+"&email="+email+'&phone=' + phone,
                cache: false,
                success: function(data) {  
                    console.log("form submitted");
                    alert("success");
                }
                });  
        return false;

   });


    //back button
    $('.back').click(function(){
        var container = $(this).parent('div'),
        previous  = container.prev();

        switch(previous.attr('id')) {
            case 'first_step' : $('#progress_text').html('0% Complete');
                  $('#progress').css('width','0px');
                       break;
            case 'second_step': $('#progress_text').html('33% Complete');
                  $('#progress').css('width','113px');
                       break;

            case 'third_step' : $('#progress_text').html('66% Complete');
                  $('#progress').css('width','226px');
                       break;

        default: break;
    }

    $(container).slideUp();
    $(previous).slideDown();
});


});

Source.

@ReactiveRaven 2012-03-09 15:31:45

My attempt at an unrestrictive regex:

/^[+#*\(\)\[\]]*([0-9][ ext+-pw#*\(\)\[\]]*){6,45}$/

Accepts:

+(01) 123 (456) 789 ext555
123456
*44 123-456-789 [321]
123456
123456789012345678901234567890123456789012345
*****++[](][((( 123456tteexxttppww

Rejects:

mob 07777 777777
1234 567 890 after 5pm
john smith
(empty)
1234567890123456789012345678901234567890123456
911

It is up to you to sanitize it for display. After validating it could be a number though.

@Stuart Kershaw 2015-04-23 22:18:44

Here's a wonderful pattern that most closely matched the validation that I needed to achieve. I'm not the original author, but I think it's well worth sharing as I found this problem to be very complex and without a concise or widely useful answer.

The following regex will catch widely used number and character combinations in a variety of global phone number formats:

/^\s*(?:\+?(\d{1,3}))?([-. (]*(\d{3})[-. )]*)?((\d{3})[-. ]*(\d{2,4})(?:[-.x ]*(\d+))?)\s*$/gm

Positive:
+42 555.123.4567
+1-(800)-123-4567
+7 555 1234567
+7(926)1234567
(926) 1234567
+79261234567
926 1234567
9261234567
1234567
123-4567
123-89-01
495 1234567
469 123 45 67
89261234567
8 (926) 1234567
926.123.4567
415-555-1234
650-555-2345
(416)555-3456
202 555 4567
4035555678
1 416 555 9292

Negative:
926 3 4
8 800 600-APPLE

Original source: http://www.regexr.com/38pvb

@Jon Schneider 2016-06-23 21:01:28

This has some limited support for extensions. It matches "616-555-1234 x567" but not "616-555-1234 ext. 567".

@mikep 2017-11-23 11:46:40

False positive for e.g."-------((((((55555555" or "99999999999999999999999"

@BIOHAZARD 2018-12-09 15:28:42

It does not validate Nitherland macdonalds number +31 76 596 4192 (I was just testing for random numbers)

@vapcguy 2014-08-14 02:00:25

I answered this question on another SO question before deciding to also include my answer as an answer on this thread, because no one was addressing how to require/not require items, just handing out regexs: Regex working wrong, matching unexpected things

From my post on that site, I've created a quick guide to assist anyone with making their own regex for their own desired phone number format, which I will caveat (like I did on the other site) that if you are too restrictive, you may not get the desired results, and there is no "one size fits all" solution to accepting all possible phone numbers in the world - only what you decide to accept as your format of choice. Use at your own risk.

Quick cheat sheet

  • Start the expression: /^
  • If you want to require a space, use: [\s] or \s
  • If you want to require parenthesis, use: [(] and [)] . Using \( and \) is ugly and can make things confusing.
  • If you want anything to be optional, put a ? after it
  • If you want a hyphen, just type - or [-] . If you do not put it first or last in a series of other characters, though, you may need to escape it: \-
  • If you want to accept different choices in a slot, put brackets around the options: [-.\s] will require a hyphen, period, or space. A question mark after the last bracket will make all of those optional for that slot.
  • \d{3} : Requires a 3-digit number: 000-999. Shorthand for [0-9][0-9][0-9].
  • [2-9] : Requires a digit 2-9 for that slot.
  • (\+|1\s)? : Accept a "plus" or a 1 and a space (pipe character, |, is "or"), and make it optional. The "plus" sign must be escaped.
  • If you want specific numbers to match a slot, enter them: [246] will require a 2, 4, or 6. [77|78] will require 77 or 78.
  • $/ : End the expression

@Ataboy Josef 2015-01-07 08:02:16

This is very useful, but I doubt and looking for a {min,max} expression. Can you help?

@vapcguy 2015-01-07 21:00:40

If it is a single digit we're talking about (and you can make it match according to that), see the [2-9] block I put there. That means your min is 2, and your max is 9. Adjust accordingly.

@Drew Thomas 2014-07-08 18:28:53

After reading through these answers, it looks like there wasn't a straightforward regular expression that can parse through a bunch of text and pull out phone numbers in any format (including international with and without the plus sign).

Here's what I used for a client project recently, where we had to convert all phone numbers in any format to tel: links.

So far, it's been working with everything they've thrown at it, but if errors come up, I'll update this answer.

Regex:

/(\+*\d{1,})*([ |\(])*(\d{3})[^\d]*(\d{3})[^\d]*(\d{4})/

PHP function to replace all phone numbers with tel: links (in case anyone is curious):

function phoneToTel($number) {
    $return = preg_replace('/(\+*\d{1,})*([ |\(])*(\d{3})[^\d]*(\d{3})[^\d]*(\d{4})/', '<a href="tel:$1$3$4$5">$1 ($3) $4-$5</a>', $number); // includes international
    return $return;
}

@Varda Elentári 2015-10-13 18:39:41

This regular expression matched +1 1234562222222222222222222222.

@thexande 2017-03-08 21:21:43

why not just return?

@Sinan Eldem 2014-04-19 21:14:19

Working example for Turkey, just change the

d{9}

according to your needs and start using it.

function validateMobile($phone)
{
    $pattern = "/^(05)\d{9}$/";
    if (!preg_match($pattern, $phone))
    {
        return false;
    }
    return true;
}

$phone = "0532486061";

if(!validateMobile($phone))
{
    echo 'Incorrect Mobile Number!';
}

$phone = "05324860614";
if(validateMobile($phone))
{
    echo 'Correct Mobile Number!';
}

@Keith Wiggans 2009-07-21 11:47:37

I was struggling with the same issue, trying to make my application future proof, but these guys got me going in the right direction. I'm not actually checking the number itself to see if it works or not, I'm just trying to make sure that a series of numbers was entered that may or may not have an extension.

Worst case scenario if the user had to pull an unformatted number from the XML file, they would still just type the numbers into the phone's numberpad 012345678x5, no real reason to keep it pretty. That kind of RegEx would come out something like this for me:

\d+ ?\w{0,9} ?\d+
  • 01234467 extension 123456
  • 01234567x123456
  • 01234567890

@Dave Kirby 2009-08-07 17:24:27

.*

If the user wants to give you his phone number, then trust him to get it right. If he does not want to give it to you then forcing him to enter a valid number will either send him to a competitor's site or make him enter a random string that fits your regex. I might even be tempted to look up the number of a premium rate sex line and enter that instead.

I would also consider any of the following as valid entries on a web site:

"123 456 7890 until 6pm, then 098 765 4321"  
"123 456 7890 or try my mobile on 098 765 4321"  
"ex-directory - mind your own business"

@Pointy 2010-11-10 18:21:24

I agree with the sentiment here, but sometimes it's nice to perform validation when the phone number is actually going to be used for something important in the interest of the user. Best example here is credit card authorization for a purchase. If the phone number is wrong, the auth might fail.

@Joel McBeth 2010-12-06 19:41:50

If the user doesn't want to enter his phone number you can just allow the field to be optional, but is it to much to ask the user to enter a valid phone number if they are going to enter one?

@Ben McIntyre 2011-02-23 00:09:39

Also a role of validation is simply to remind people to add area codes etc that they might not otherwise remember to add, but which cannot possibly be guessed after the fact.

@Benjol 2011-03-01 12:14:21

@Pointy: Yes, but even if it's a valid number, that doesn't mean it's an existing number, and even if it's existing, that doesn't mean that it is the users'. If it's that important, you need to set up an automated system that phones them up to check... If your budget stretches that far :)

@Pointy 2011-03-01 12:52:21

@Benjol yes that's true - my personal feeling here is probably affected by the fact that one of my laptops has a sticky "5" key :-)

@Chris Peterson 2011-04-01 22:37:31

I agree from a usability perspective, but allowing arbitrary input may expose your website to cross-site scripting (XSS) attacks. A malicious user might be able to inject JavaScript in your free-form phone number string.

@PlexQ 2012-03-30 17:14:11

Sometimes users have to give a valid phone number. If you state that it's part of the ToS to give one, they can't give a fake one without being in violation. If you at least make sure from a validation perspective that what they gave is syntactically correct, it will save a lot of headaches.

@Cory Mawhorter 2012-09-28 19:35:09

I usually tend to gravitate towards this way of thinking with user experience. A valid US phone number at the core is 10 digits: ^(.*\d.*){10,}$. That allows it to be entered in any way the user would like. Then, on the backend, strip out invalid characters.

@Alex B 2012-11-16 06:40:19

@Pointy But regex validation won't help you. The one and the only way to actually validate if the phone number is correct is to actually send a message to it (in case of mobile) AND make sure the user confirms using some kind of verification code. This is what you do when the number correctness is important. Everything else is just for user's convenience to protect against some (but not all) typos and does not validate anything.

@Pointy 2012-11-16 13:42:13

@AlexB well sure, I understand that, but if you can help me catch the error of leaving off a digit, it saves me the (slight) inconvenience of getting a server-side error, interpreting it, finding the field again, etc.

@Jason 2013-01-22 19:33:02

There are a million use cases where this plain text solution is the answer. But there are a million use cases where this would cause many many problems. Look at how you are using the phone number and why you are asking for it. Then you can decide which methodology is right for you. If you don't know why you are asking or how you are using it, you probably shouldn't be asking for a phone number in the first place.

@user2069217 2013-09-03 14:38:08

True, but then you could just do something along the lines of 'when is not empty, validate'. Something like if (!empty($telephone) && !validation_function($telephone)) { //throw_error } then you can choose NOT to input your number.

@Aaron Newton 2013-09-19 08:31:24

Cool. My phone number is 1' OR 1=1 -- PWNED. See xkcd.com/327 and owasp.org/index.php/Testing_for_SQL_Injection_(OWASP-DV-005)

@Ziggy 2014-01-08 14:15:28

The answer contains the deepest wisdom.

@Evan Donovan 2014-01-24 17:05:40

In my case, I needed to validate the phone number since it was the easiest way to find who was spamming the form. The spammers were the ones using invalid phone numbers. Plus, it was a inquiry form, so we were planning on calling all the people who filled it out, and phone number was a required field.

@Mark 2014-04-10 11:49:09

@EvanDonovan Then you will miss my entry as I will use a dummy phone unless I want you to call me which is very unlikely

@Evan Donovan 2014-04-11 15:15:19

@Mark: I'm not too concerned about that. Obviously I can't capture everything with a regex. In this case, the spammers were not putting any valid data into the form, whereas I am presuming that if you were filling out the form, you would at least be putting in a valid email.

@darkheartfelt 2015-01-07 23:09:41

This answer does not answer the question - rather it just promotes intolerance of forms, which is already inherent in us all.

@Willem Van Onsem 2015-02-18 17:21:13

@AaronNewton: performing validation at the form level or using regexes is unsafe anyway, there are better ways to prevent sql injection.

@Aaron Newton 2015-02-19 01:17:44

@CommuSoft that's completely true. However, a better statement might be don't rely solely on regex for prevention of SQL injection. I would still argue that it makes sense to check for obviously wrong or nefarious input, e.g. can you think of a case where a phone number needs anything other than alpha-numerics + basic punctuation, or needs to be longer than the length of the field in the database? Regarding the latter, it is likely to confuse and or annoy the user if the database field is 128 characters but you allow the user to enter 129 characters, resulting in some error on the UI.

@Mike Manard 2015-07-23 22:31:02

This response is irreverent and in no way relevant to the question. The OP asked for help validating the format of input from a user; not for your personal opinion about whether he should. Potential use case: The website is for a company's internal usage - not meaning intranet usage, but rather this company has employees that work "out in the field" and communicate with in-office employees via this website. They need the person to enter a valid phone number at which they can be reached, as part of their job requirements, and want to avoid simple mistakes that could cause headaches.

@lee 2015-10-13 19:15:40

.* is a regex which will validate zero or more characters of any type as valid, which misses the goal of phone number validation.

@DrewB 2016-10-12 12:14:45

Of course that doesn't take into account forms that do require a phone number. I'm currently building an app to keep track of licensing information within our organization. Vendor phone numbers are required so I'd certainly like to validate them.

@Tom Lord 2016-10-26 09:23:10

If you want to truly validate a phone number... PHONE IT!! This is just like the ridiculous regular expressions people have come up with to "validate an email address"... If you really care that the email address is valid, then SEND THEM AN EMAIL!!

@Romeno 2016-12-16 01:37:44

-1 because you can make the field NOT required and still need to validate it to help prevent accidental misspells. The part of the answer with 'or try my mobile on' is just rubbish IMO. You give the format its user decision to follow it or not. Just dont make it required thats all.

@Yarin 2017-11-09 18:46:12

Question was not about user input validation. Could be validating a list of aggregated phone numbers from multiple systems, collected at different times via different forms. Dirty data comes from all sorts of places.

@ron0 2009-04-10 12:21:10

If you're talking about form validation, the regexp to validate correct meaning as well as correct data is going to be extremely complex because of varying country and provider standards. It will also be hard to keep up to date.

I interpret the question as looking for a broadly valid pattern, which may not be internally consistent - for example having a valid set of numbers, but not validating that the trunk-line, exchange, etc. to the valid pattern for the country code prefix.

North America is straightforward, and for international I prefer to use an 'idiomatic' pattern which covers the ways in which people specify and remember their numbers:

^((((\(\d{3}\))|(\d{3}-))\d{3}-\d{4})|(\+?\d{2}((-| )\d{1,8}){1,5}))(( x| ext)\d{1,5}){0,1}$

The North American pattern makes sure that if one parenthesis is included both are. The international accounts for an optional initial '+' and country code. After that, you're in the idiom. Valid matches would be:

  • (xxx)xxx-xxxx
  • (xxx)-xxx-xxxx
  • (xxx)xxx-xxxx x123
  • 12 1234 123 1 x1111
  • 12 12 12 12 12
  • 12 1 1234 123456 x12345
  • +12 1234 1234
  • +12 12 12 1234
  • +12 1234 5678
  • +12 12345678

This may be biased as my experience is limited to North America, Europe and a small bit of Asia.

@Jannis 2010-10-17 20:07:48

I've been trying to implement the above in my javascript validation script but I keep getting an invalid quantifier error. Any ideas on what I'm doing wrong?

@rupps 2015-04-19 23:12:04

I'd add the trivial case where the phone is specified without symbols but maybe spaces and country code, in Europe is typical for local and mobile numbers: 676412342, 676 46 32 12, 676 463 212

@GaiusSensei 2012-01-18 01:23:47

This is a simple Regular Expression pattern for Philippine Mobile Phone Numbers:

((\+[0-9]{2})|0)[.\- ]?9[0-9]{2}[.\- ]?[0-9]{3}[.\- ]?[0-9]{4}

or

((\+63)|0)[.\- ]?9[0-9]{2}[.\- ]?[0-9]{3}[.\- ]?[0-9]{4}

will match these:

+63.917.123.4567  
+63-917-123-4567  
+63 917 123 4567  
+639171234567  
09171234567  

The first one will match ANY two digit country code, while the second one will match the Philippine country code exclusively.

Test it here: http://refiddle.com/1ox

@stormwild 2014-02-26 05:41:02

Thanks. How about landline numbers with area code such as 028231234? I'm wondering if area codes are only 2-3 digit numbers and are they always preceded by 0?

@Steve 2012-08-15 21:21:13

If you just want to verify you don't have random garbage in the field (i.e., from form spammers) this regex should do nicely:

^[0-9+\(\)#\.\s\/ext-]+$

Note that it doesn't have any special rules for how many digits, or what numbers are valid in those digits, it just verifies that only digits, parenthesis, dashes, plus, space, pound, asterisk, period, comma, or the letters e, x, t are present.

It should be compatible with international numbers and localization formats. Do you foresee any need to allow square, curly, or angled brackets for some regions? (currently they aren't included).

If you want to maintain per digit rules (such as in US Area Codes and Prefixes (exchange codes) must fall in the range of 200-999) well, good luck to you. Maintaining a complex rule-set which could be outdated at any point in the future by any country in the world does not sound fun.

And while stripping all/most non-numeric characters may work well on the server side (especially if you are planning on passing these values to a dialer), you may not want to thrash the user's input during validation, particularly if you want them to make corrections in another field.

@Droogans 2012-08-24 15:52:17

I wouldn't recomend using a regex for this.

Like the top answer, strip all the ugliness from the phone number, so that you're left with a string of numeric characters, with an 'x', if extensions are provided.

In Python:

Note: BAD_AREA_CODES comes from a text file that you can grab from on the web.

BAD_AREA_CODES = open('badareacodes.txt', 'r').read().split('\n')

def is_valid_phone(phone_number, country_code='US'):
    """for now, only US codes are handled"""
    if country_code:
        country_code = country_code.upper()

    #drop everything except 0-9 and 'x'
    phone_number = filter(lambda n: n.isdigit() or n == 'x', phone_number)

    ext = None
    check_ext = phone_number.split('x')
    if len(check_ext) > 1:
        #there's an extension. Check for errors.
        if len(check_ext) > 2:
            return False
        phone_number, ext = check_ext

    #we only accept 10 digit phone numbers.
    if len(phone_number) == 11 and phone_number[0] == '1':
        #international code
        phone_number = phone_number[1:]
    if len(phone_number) != 10:
        return False

    #area_code: XXXxxxxxxx 
    #head:      xxxXXXxxxx
    #tail:      xxxxxxXXXX
    area_code = phone_number[ :3]
    head      = phone_number[3:6]
    tail      = phone_number[6: ]

    if area_code in BAD_AREA_CODES:
        return False
    if head[0] == '1':
        return False
    if head[1:] == '11':
        return False

    #any other ideas?
    return True

This covers quite a bit. It's not a regex, but it does map to other languages pretty easily.

@Richard Ayotte 2012-05-13 19:47:55

Here's one that works well in JavaScript. It's in a string because that's what the Dojo widget was expecting.

It matches a 10 digit North America NANP number with optional extension. Spaces, dashes and periods are accepted delimiters.

"^(\\(?\\d\\d\\d\\)?)( |-|\\.)?\\d\\d\\d( |-|\\.)?\\d{4,4}(( |-|\\.)?[ext\\.]+ ?\\d+)?$"

@Abe Miessler 2011-08-11 05:10:29

You would probably be better off using a Masked Input for this. That way users can ONLY enter numbers and you can format however you see fit. I'm not sure if this is for a web application, but if it is there is a very click jQuery plugin that offers some options for doing this.

http://digitalbush.com/projects/masked-input-plugin/

They even go over how to mask phone number inputs in their tutorial.

@mindplay.dk 2011-04-14 20:56:45

My gut feeling is reinforced by the amount of replies to this topic - that there is a virtually infinite number of solutions to this problem, none of which are going to be elegant.

Honestly, I would recommend you don't try to validate phone numbers. Even if you could write a big, hairy validator that would allow all the different legitimate formats, it would end up allowing pretty much anything even remotely resembling a phone number in the first place.

In my opinion, the most elegant solution is to validate a minimum length, nothing more.

@Christopher King 2014-01-17 15:12:34

After trying a number of these and going through the existing data and feedback from users i would tend to agree...

@Chris 2011-01-04 19:51:29

I found this to be something interesting. I have not tested it but it looks as if it would work

<?php
/*
string validate_telephone_number (string $number, array $formats)
*/

function validate_telephone_number($number, $formats)
{
$format = trim(ereg_replace("[0-9]", "#", $number));

return (in_array($format, $formats)) ? true : false;
}

/* Usage Examples */

// List of possible formats: You can add new formats or modify the existing ones

$formats = array('###-###-####', '####-###-###',
                 '(###) ###-###', '####-####-####',
                 '##-###-####-####', '####-####', '###-###-###',
                 '#####-###-###', '##########');

$number = '08008-555-555';

if(validate_telephone_number($number, $formats))
{
echo $number.' is a valid phone number.';
}

echo "<br />";

$number = '123-555-555';

if(validate_telephone_number($number, $formats))
{
echo $number.' is a valid phone number.';
}

echo "<br />";

$number = '1800-1234-5678';

if(validate_telephone_number($number, $formats))
{
echo $number.' is a valid phone number.';
}

echo "<br />";

$number = '(800) 555-123';

if(validate_telephone_number($number, $formats))
{
echo $number.' is a valid phone number.';
}

echo "<br />";

$number = '1234567890';

if(validate_telephone_number($number, $formats))
{
echo $number.' is a valid phone number.';
}
?>

@Alastair Irvine 2013-09-30 03:33:34

Your message seems to indicate that you didn't write this code. Would you mind citing a source, please?

@James Paterson 2016-01-12 15:40:02

@Ian 2011-02-28 23:16:18

    pattern="^[\d|\+|\(]+[\)|\d|\s|-]*[\d]$" 
    validateat="onsubmit"

Must end with a digit, can begin with ( or + or a digit, and may contain + - ( or )

@Justin R. 2008-09-23 20:32:39

It turns out that there's something of a spec for this, at least for North America, called the NANP.

You need to specify exactly what you want. What are legal delimiters? Spaces, dashes, and periods? No delimiter allowed? Can one mix delimiters (e.g., +0.111-222.3333)? How are extensions (e.g., 111-222-3333 x 44444) going to be handled? What about special numbers, like 911? Is the area code going to be optional or required?

Here's a regex for a 7 or 10 digit number, with extensions allowed, delimiters are spaces, dashes, or periods:

^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:\(\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*(?:#|x\.?|ext\.?|extension)\s*(\d+))?$

@DJTripleThreat 2010-05-04 04:37:59

here it is without the extension section (I make my users enter ext in a separate field): ^(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:(\s*([2-9]1[02-9]|[2-9][0‌​2-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})$

@Brian Surowiec 2010-08-20 16:58:06

This worked nicely for me. I needed to update the extension part though by adding a slash before the #, otherwise it says from there over is a comment

@Jeremy Ricketts 2010-09-01 03:23:26

What about adding "(" and ")" to that list of delimiters?

@Brian Armstrong 2010-09-07 19:32:24

Here is a version that only matches 10 digit phone numbers (not 7 digit like 843-1212): /(?:(?:\+?1\s*(?:[.-]\s*)?)?(?:(\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})/

@BandonRandon 2011-01-09 05:09:58

10 digit accepts () around area code, and dosen't allow preceeding 1 as country code (?:(?:(\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})

@Justin R. 2013-03-28 21:06:21

@StevenSoroka I have had Jeffrey Friedl's book beside me on my desk for the past two years, as regular expressions are a major part of my work. It takes a good while to really understand regular expressions. Sometimes, the readers of this site are simply looking for an existing soltuion, rather than writing their own, especially in domains with lots of corner cases, such as phone number representations.

@Steven Soroka 2013-04-05 21:49:56

@fatcat1111 I understand that, but majority of the responses here are "me too" type of one-off regular expressions that likely don't fit any of your corner cases. These then end up on all the websites I'm trying to use and I can't enter my zip code or phone number or email address because someone used a half-baked regular-expression (eg: + is a valid character in email addresses). The best responses on this page point users to libraries, not to napkin-scrawled regexes.

@Nate Glenn 2015-12-17 02:47:19

Be careful to check for non-breaking spaces when copying these expressions.

@ThisSuitIsBlackNot 2016-05-16 22:13:31

I wonder if something changed since you first posted this. It doesn't match at least one valid area code: 410 (Maryland). 410 is mentioned in the Wikipedia article you linked to, but 410 has been in service since 1991.

Related Questions

Sponsored Content

77 Answered Questions

[SOLVED] How to validate an email address in JavaScript?

48 Answered Questions

[SOLVED] Validate decimal numbers in JavaScript - IsNumeric()

27 Answered Questions

[SOLVED] (Built-in) way in JavaScript to check if a string is a valid number

70 Answered Questions

35 Answered Questions

[SOLVED] RegEx match open tags except XHTML self-contained tags

  • 2009-11-13 22:38:26
  • Jeff
  • 2474123 View
  • 1324 Score
  • 35 Answer
  • Tags:   html regex xhtml

1 Answered Questions

[SOLVED] iPhone phone number format NSFormatter

3 Answered Questions

[SOLVED] regular expression phone number

14 Answered Questions

[SOLVED] How to mark-up phone numbers?

2 Answered Questions

[SOLVED] Regex Phone number with dashes

  • 2015-06-30 16:13:35
  • Bojan
  • 437 View
  • 1 Score
  • 2 Answer
  • Tags:   regex

1 Answered Questions

[SOLVED] What is the best regular expression for phone numbers?

  • 2012-12-05 08:53:17
  • Gerard Nijboer
  • 8989 View
  • 2 Score
  • 1 Answer
  • Tags:   regex phone-number

Sponsored Content