USA’s phone number validation using Regular expression in PHP
- Friday, February 8, 2008, 10:06
- php, tips and technique, tutorial
- 8 comments
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.
Popularity: 6% [?]
Related Posts
» Php function to validate two decimal places of a number
» Getting random number between range of two numbers in JavaScript
» Characteristics of experienced programmer
» W3c markup validation and Big websites – Is it really needed?





Actually, I don’t think the exchange (middle 3) can start with a 1 or 0 either
thank uuuuuuuuuuuuuuuuuuuuuuuu!
I tried this code in my order form on the site and it works perfectly, just what I needed.
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}
It’s possible things like what you mention might change in the future steve
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!
very helpful thank you for sharing