Friday 27 February 2009

International Phone Number Format FunctionInternational Phone Number Format Function

Left QuoteThis 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.


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


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.Right Quote

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

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


Add your comments




8 + 6 = (this security question stops automated submissions)