USA’s phone number validation using Regular expression in PHP

Last day i saw that one of my friend looking for the validation script in PHP which post the phone no (number) of USA from the text box and wanted to validate it from PHP in the following format.

“XXX-XXX-XXXX”

Well, I’ve made a function in PHP for him to validate the north American phone number format.Here is that function which might be useful for you.

function validatePhoneNo($phone)
{
  if(ereg('^[2-9]{1}[0-9]{2}-[0-9]{3}-[0-9]{4}$', $phone))
     return true;
  else
     return false;
}

Now lets look at the explanation of following regular expression I’ve used in ereg() function of PHP.

^[2-9]{1}[0-9]{2}-[0-9]{3}-[0-9]{4}$

The first hat sign (^) represents that it is the beginning of the string. And [2-9]{1} represents that is the first character should be digits ranging from 2 to 9 and the next [0-9]{2} represents that the next two characters should be digits ranging from 0 to 9. And the dash () next to it represents that this character must exists. And the next [0-9]{3} means that the next three characters should be digits and the next expression also means that there should be existence of dash () and three digits and the last string dollar sign ($) represents that it is the end of the string.

8 thoughts on “USA’s phone number validation using Regular expression in PHP

  1. Kevin

    Actually, I don’t think the exchange (middle 3) can start with a 1 or 0 either

  2. g.j.srinivas

    thank uuuuuuuuuuuuuuuuuuuuuuuu!

  3. I tried this code in my order form on the site and it works perfectly, just what I needed.

    Steve

  4. Steve

    This is incorrect.

    The 4 digit (1 after area code) can never start with a 0 or a 1. It can be 2-9 only.

    Valid: 5552221234
    Invalid: 5551231234

    Thus the correct regexp is:
    [2-9]{1}[0-9]{2}[2-9]{1}[0-9]{2}[0-9]{4}

  5. It’s possible things like what you mention might change in the future steve :-)

  6. Thanks for you help, I have a web form and get spammers putting 12345 as their # all the time! How would I incorporate this into a standard php contact form? Thanks for you time and the script!

  7. very helpful thank you for sharing

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>