美国邮政编码验证

4

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

我使用以下表达式进行验证:

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

然而,它无法验证所有的00000或11111等类似数字。
如何验证不正确的邮政编码,例如那些不属于美国邮政编码的五位数。

它对我有效。 - 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'; } - MonkeyZeus
Satyendra,你在确保数据质量方面做得很好 - 只是要注意并非每个人都有5位数字的邮政编码!http://stackoverflow.com/questions/22620156/making-sure-that-a-user-cant-submit-less-than-5-numbers-for-zip-code-in-a-javas/22631342#22631342 Al. - Al Mills
尝试查看这个讨论:https://dev59.com/2nVC5IYBdhLWcg3w21Iq - Ernesto Rendon
4个回答

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接