How Can I Validate the Phone Number?

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
Tayla6
Forum Commoner
Posts: 26
Joined: Thu Oct 10, 2013 8:40 am
Location: Manchester
Contact:

How Can I Validate the Phone Number?

Post by Tayla6 »

I want to validate the phone number using a regular expression. Phone number should be global. It may contain special characters like "hypen" or "Paranthesis".
Tayla the great
Eric!
DevNet Resident
Posts: 1146
Joined: Sun Jun 14, 2009 3:13 pm

Re: How Can I Validate the Phone Number?

Post by Eric! »

You can find lots of regexs on the internet to suit your needs. I don't know specifically what you mean by a "global" phone number but here's a regex I've used in the past with some test cases. There are some international phone numbers with an extra digit that fails this regex.

Code: Select all

$numbers[]='+1 404-223-1122';
$numbers[]='1-234-567-8901';
$numbers[]='1-234-567-8901 x1234';
$numbers[]='1-234-567-8901 ext1234';
$numbers[]='1 (234) 567-8901';
$numbers[]='1.234.567.8901';
$numbers[]='1/234/567/8901'; //fails
$numbers[]='12345678901';

foreach($numbers as $number){
  echo $number.'=';
  if(preg_match('/^(?:(?:\+?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+))?$/',$number)){
    echo "Pass\n";
  }
  else {
    echo "Fail\n";
  }
}
User avatar
requinix
Spammer :|
Posts: 6617
Joined: Wed Oct 15, 2008 2:35 am
Location: WA, USA

Re: How Can I Validate the Phone Number?

Post by requinix »

Best method I know: strip everything but the numbers and check the length. Then reformat however you want.

If you want extensions, allow letters too and then do a regex (because it's easier than the alternatives). Even then all you really need is to check the lengths of numbers.
Eric!
DevNet Resident
Posts: 1146
Joined: Sun Jun 14, 2009 3:13 pm

Re: How Can I Validate the Phone Number?

Post by Eric! »

I used to do that, but I ran into problems where different regions like the phone numbers to be formatted differently. Like in Mexico they like to group numbers by 2's. So I found it easier to try to work with whatever format user's were used to using.
regexer
Forum Newbie
Posts: 4
Joined: Sat Dec 20, 2014 6:38 pm

Re: How Can I Validate the Phone Number?

Post by regexer »

With this tool you can enter your variants and generate regex based on them http://www.regex-builder.com/
http://www.regex-builder.com/ online regular expression composer based on text analysis
Post Reply