captainash.com

International Phone Number Format Function

This regular expression allows anything that starts with a "+" and 1-3 digits for the country code, followed by an optional "-" or space, followed by an optional digit in brackets (typically 0) followed by either two or three blocks of 1-7 digits.

PHP



function invalidPhoneNumber($str) {
if (preg_match("/^(\+\d{1,3}(-| )?\(?\d\)?(\s?\d{1,7}){2,3})$/", $str)) return false;
else return true;
}


JavaScript



function invalidPhoneNumber(str) {
if (str.match(/^(\+\d{1,3}(-| )?\(?\d\)?(\s?\d{1,7}){2,3})$/)) return false;
else return true;
}


This way it picks up a one-digit area code, and works for UK (+44 xxxx xxxxxx), US (+1 xxx xxx xxxx) and NZ (+64 x xxx xxxx) number formats. It’s not the strictest of rules, but it forces people into using the right basic format.

These functions return true if the input is invalid, as they are error-checking functions. The code can then be writted if (invalidPhoneNumber(str)) which is nice and easy to read.

Next article: Hiding email addresses with PHP (04 March 2009)

Next Websites article: Creating Multipart Emails in PHP (15 June 2009)

--- Posted in Websites and viewed 8,421 times ---


Add your comments

3 + 5 = (this security question stops automated submissions)