有人可以告诉我如何使用正则表达式验证美国的邮政编码吗?
我使用以下表达式进行验证:
var us_postcode_regular = /^([0-9]{5})(?:[-\s]*([0-9]{4}))?$/;
然而,它无法验证所有的00000或11111等类似数字。
如何验证不正确的邮政编码,例如那些不属于美国邮政编码的五位数。
有人可以告诉我如何使用正则表达式验证美国的邮政编码吗?
我使用以下表达式进行验证:
var us_postcode_regular = /^([0-9]{5})(?:[-\s]*([0-9]{4}))?$/;
if(ctype_digit($zip) && strlen($zip) == 5){ echo 'US Zip Code'; }
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"
}
]
}
我相信,你可以使用最简单的这个:
function validateUSAZip($zip_code) {
return preg_match(“/^([0-9]{5})(-[0-9]{4})?$/i”,$zip_code);
}
它实际上使用了与你的类似的正则表达式。
<!-- 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
if(ctype_digit($zip) && strlen($zip) == 5){ echo 'US Zip Code'; }
- MonkeyZeus