Javascript Phone Number Validation Regex
Adheres to the US North American Numbering Plan
http://en.wikipedia.org/wiki/North_American_Numbering_Plan
validate_phone("16505217791x1234") == "(650)521-7791 x1234";
validate_phone("16505217791x") == "(650)521-7791";
validate_phone("6505217791") == "(650)521-7791";
validate_phone("1234567890") == null;
validate_phone("12345678901") == "(234)567-8901";PHP
function validate_phone($num) { $num = preg_replace("/[^x0-9]/",'',$num); $num = preg_replace("/^1/",'',$num); $regx = "/^([2-9][0-8][0-9])([2-9][0-9]{2})([0-9]{4})x?([0-9]{1,})?$/"; $match = preg_match($regx, $num, $m); if($match) { return "(".$m[1].")".$m[2]."-".$m[3].($m[4]?" x".$m[4]:""); } }
Javascript
function validate_phone(num) { num = num.replace(/[^x0-9]/g,'') num = num.replace(/^1/,''); var regx = /^([2-9][0-8][0-9])([2-9][0-9]{2})([0-9]{4})x?([0-9]{1,})?$/; var m = num.match(regx); if(m) { return "("+m[1]+")"+m[2]+"-"+m[3]+(m[4]!=undefined?' x'+m[4]:''); } }
Comments(0)