views:

128

answers:

3

I need to validate an Irish phone number but I don't want to make it too user unfriendly, many people are used to writing there phone number with brackets wrapping their area code followed by 5 to 7 digits for their number, some add spaces between the area code or mobile operator.

The format of Irish landline numbers is an area code of between 1 and 4 digits and a number of between 5 to 8 digits.

e.g.

(021) 9876543
(01)9876543
01 9876543
(0402)39385

I'm looking for a regular expression for Javascript/PHP.

Thanks.

+1  A: 

Try this one:

http://regexlib.com/REDetails.aspx?regexp_id=2485

Modified version excluding the area code:

\d{3}\s\d{4}
Simon Brown
Hi Simon, cheers for the reply, I don't want the country code because I'm handling that seperately and using `/^\(0\)\s\d\s\d{3}\s\d{4}$/` doesn't seem to work the way I want
Eoghan O'Brien
+2  A: 

This might work. It should account for appearances of spaces anywhere in phone number.

preg_match('|^\s*\(?\s*\d{1,4}\s*\)?\s*[\d\s]{5,10}\s*$|', $phone);

People sometimes split phone number part into 2 parts by spaces.

Update: if you wish to validate phone number and trim spaces at the same time, you can do it like this:

if (preg_match('|^\s*(\(?\s*\d{1,4}\s*\)?\s*[\d\s]{5,10})\s*$|', $phone, $m))
{
    echo $m[1];
}
mr.b
That's awesome. Almost perfect. Is there anyway to trim the space at the beginning and the end?
Eoghan O'Brien
Either use trim($phone) before matching, or put ( and ) after and before first/final \s* in matching string, and then read first matched string. I'll update my answer.
mr.b
Thanks mr.b, I'm already trimming on the server side, I just wanted to do it on the client side aswell, I'm using $.trim in jQuery but I also wanted it to fail if the spaces were there. Although, thinkiing about it again, it seems like overkill.
Eoghan O'Brien
+1  A: 

If it were me, I'd strip spaces and brackets, then verify it's between the minimum and maximum length.

Rich Bradshaw
+1, that's how I'd do it.
Josh