【问题标题】:Zipcode validation for US美国邮政编码验证
【发布时间】:2013-10-09 07:14:17
【问题描述】:

谁能告诉我如何使用正则表达式验证美国的邮政编码。

我使用下面的表达式进行验证

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

但它无法验证所有 00000 或 11111 或类似数字。

以及如何验证不正确的邮政编码,例如不属于美国邮政编码的五位数字。

【问题讨论】:

  • 该模式已经正确。您无法从正则表达式中真正确定有效的邮政编码;您只能判断它的格式是否正确(5 位或 9 位)。
  • 如果您想确保邮政编码存在,请查看 USPS 的地址验证 API:usps.com/business/web-tools-apis/address-information.htm
  • 这样做有什么问题:if(ctype_digit($zip) && strlen($zip) == 5){ echo 'US Zip Code'; }
  • 确保您的数据质量的良好开端 Satyendra - 请注意,并非每个人都有 5 位数的邮政编码! stackoverflow.com/questions/22620156/…Al.

标签: javascript php validation


【解决方案1】:
if(ctype_digit($zip) && strlen($zip) == 5){ echo 'US Zip Code'; }

【讨论】:

    【解决方案2】:

    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"
        }
    ]
    

    }

    【讨论】:

      【解决方案3】:

      我相信,您可以使用的最简单的是:

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

      它实际上使用了和你类似的正则表达式。

      【讨论】:

        【解决方案4】:
        <!-- 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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-05-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-07-24
          相关资源
          最近更新 更多