2013-10-02 108 views
2

任何人都可以告诉我如何使用正则表达式验证美国的邮政编码。美国的邮政编码验证

我用以下表达式进行验证

var us_postcode_regular = /^([0-9]{5})(?:[-\s]*([0-9]{4}))?$/; 

但是它不能够验证所有00000或11111或类似的号码。

以及如何验证不正确的邮政编码,如五个数字不是美国邮政编码的一部分。

+0

它[**为我工作。**](http://regexr.com?36itk) – theftprevention

+2

这种模式已经是正确的。您无法从正则表达式中真正确定有效的邮政编码;你只能告诉它是否在正确的形式(5或9位数字)。 – Pointy

+3

如果您想确保邮政编码存在,请查看USPS的地址验证API:https://www.usps.com/business/web-tools-apis/address-information.htm – aynber

回答

1
if(ctype_digit($zip) && strlen($zip) == 5){ echo 'US Zip Code'; } 
0

http://www.zipcodeapi.com/API#zipToLoc这样做很简单。呼叫的样子:

http://www.zipcodeapi.com/rest/<api_key>/info.<format>/<zip_code>/<units> 

坏拉链码将抛出,你可以捕获错误。有效的邮编将返回一个JSON(或XML或CSV)的反应是这样的:

{ 
"zip_code": "08057", 
"lat": 56.595452, 
"lng": -69.784543, 
"city": "Classified", 
"state": "NJ", 
"timezone": { 
    "timezone_identifier": "America/New_York", 
    "timezone_abbr": "EDT", 
    "utc_offset_sec": -14400, 
    "is_dst": "T" 
}, 
"acceptable_city_names": [ 
    { 
     "city": "Classified", 
     "state": "NJ" 
    }, 
    { 
     "city": "Classified", 
     "state": "NJ" 
    } 
] 

}

0

我相信,你可以用最简单的一个是这样的:

function validateUSAZip($zip_code) { 
return preg_match(“/^([0-9]{5})(-[0-9]{4})?$/i”,$zip_code); 
} 

这是实际上使用类似你的正则表达式。

-1
<!-- Hi developers this is a simple demo for **zip code validation for us country** And this code is very usefull for you. --> 

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
    <title>Validate US Zip Code in JavaScript</title> 
    <script type="text/javascript"> 
     function IsValidZipCode(zip) { 
      var isValid = /^[0-9]{5}(?:-[0-9]{4})?$/.test(zip); 
      if (isValid) 
       alert('Valid ZipCode'); 
      else { 
       alert('Invalid ZipCode'); 
      } 
     } 
    </script> 
</head> 
<body> 
<form> 
<input id="txtZip" name="zip" type="text" /><br /> 
<input id="Button1" type="submit" value="Validate"onclick="IsValidZipCode(this.form.zip.value)" /> 
</form> 
</body> 
</html> 

欲了解更多信息。 http://www.devcurry.com/2010/07/validate-us-zip-code-using-javascript.html