How Can I Validate the Phone Number?
Moderator: General Moderators
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".
Tayla the great
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.
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";
}
}
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.
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.
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.
Re: How Can I Validate the Phone Number?
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