PHP Developers Network
http://forums.devnetwork.net/

How Can I Validate the Phone Number?
http://forums.devnetwork.net/viewtopic.php?f=38&t=138813
Page 1 of 1

Author:  Tayla6 [ Wed Nov 27, 2013 9:07 am ]
Post subject:  How Can I Validate the Phone Number?

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".

Author:  Eric! [ Wed Nov 27, 2013 2:22 pm ]
Post subject:  Re: How Can I Validate the Phone Number?

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.

Syntax: [ Download ] [ Hide ]
$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";
  }
}

Author:  requinix [ Wed Nov 27, 2013 4:55 pm ]
Post subject:  Re: How Can I Validate the Phone Number?

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.

Author:  Eric! [ Wed Nov 27, 2013 7:00 pm ]
Post subject:  Re: How Can I Validate the Phone Number?

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.

Author:  regexer [ Sat Dec 20, 2014 7:52 pm ]
Post subject:  Re: How Can I Validate the Phone Number?

With this tool you can enter your variants and generate regex based on them

Page 1 of 1 All times are UTC - 5 hours
Powered by phpBB® Forum Software © phpBB Group
http://www.phpbb.com/