By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
437,831 Members | 2,296 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 437,831 IT Pros & Developers. It's quick & easy.

preg_match method to validate phone numbers

uranuskid
P: 19
Hey folks,

I'd like to validate phone number field. Any number in the formate xx-xxx-xxx(xx)
is supposed to pass the test (where x in brackets are optional). Here is what i used, but it doesn't work:
[PHP]if (!preg_match("/^[0-9]{2,2}[-]{1,1}[0-9]{3,3}[-]{1,1}[0-9]{3,5}$/", $phone)
{ echo "<p> Eroor message</p>";}

[/PHP]

I reckon it's just a matter of defining the optional fields, however, I don't know how. Any help would be most appreciated.

Cheers,
Frank
May 9 '07 #1
Share this Question
Share on Google+
2 Replies


pbmods
Expert 5K+
P: 5,821
[PHP]if (!preg_match("/^[0-9]{2,2}[-]{1,1}[0-9]{3,3}[-]{1,1}[0-9]{3,5}$/", $phone)
{ echo "<p> Eroor message</p>";}
[/PHP]
You've got a pretty complicated regex there, but it doesn't have to be:

[PHP]
if(! preg_match('/^\d{2}-\d{3}-\d{3}(\d{2})?$/', $phone)) {
echo "<p> Error message</p>";
}
[/PHP]

Or if you wanted to get really compact...

[PHP]
if(! preg_match('/^\d{2}(-\d{3}){2}(\d{2})?$/', $phone)) {
echo "<p> Error message</p>";
}
[/PHP]

http://www.regular-expressions.info/reference.html
May 10 '07 #2

uranuskid
P: 19
You've got a pretty complicated regex there, but it doesn't have to be:

[PHP]
if(! preg_match('/^\d{2}-\d{3}-\d{3}(\d{2})?$/', $phone)) {
echo "<p> Error message</p>";
}
[/PHP]

Or if you wanted to get really compact...

[PHP]
if(! preg_match('/^\d{2}(-\d{3}){2}(\d{2})?$/', $phone)) {
echo "<p> Error message</p>";
}
[/PHP]

http://www.regular-expressions.info/reference.html
Hey,

I tried your suggestions, however, wouldn't work for my purpose as the two last numbers are optional, so either one or two or none!

I got more into Regex and redefined my preg_match patter like this:
[PHP]
if(! preg_match('/^[0]{1}[3-9]{1}-\d{3}-\d{4}(\d{1,2})?$/',$phone))
{ echo "<p> Error message </p>"}
[/PHP]
I redefined the first two numbers as they should match NZ landlines!

Well, thanks anyway, especially for the link, it's a really good reference!!

Aloha,
Frank
May 11 '07 #3

Post your reply

Sign in to post your reply or Sign up for a free account.