如何使用 jQuery 验证插件验证美国邮政编码

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19011993/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 22:59:32  来源:igfitidea点击:

How to validate US ZIP code using jQuery Validation plugin

javascriptjqueryasp.net-mvcjquery-validate

提问by UID

I am using the jQuery Validation pluginfor validating my form.

我正在使用jQuery 验证插件来验证我的表单。

I want to validate the zip code as per US ZIPCode format :-

我想按照美国邮政编码格式验证邮政编码:-

> 12345
> 12345-6789
> 12345 6789

As per my curent code its validating the zipcode should be maximum 5 and all numeric.

根据我当前的代码,它验证邮政编码的最大值应为 5 且全部为数字。

Please see the code below:

请看下面的代码:

    <script src="~/Scripts/js/jquery.validate.js"></script>

<script>

    $().ready(function () {

        // validate signup form on keyup and submit
        $("#locationSetup").validate({
            rules: {
                'Address.AddressStreet': "required",
                'Address.City': "required",
                'Address.State.Country.CountryIsoCode': "required",
                'Address.State.SubnationalIsoCode': "required",
                'Address.PostalCode': {
                    required: true,
                    minlength: 5,
                    maxlength: 5,
                    digits: true
                }
            },
            messages: {
                'Address.AddressStreet': "Please enter your Street Address!",
                'Address.City': "Please select your City!",
                'Address.State.Country.CountryIsoCode': "Please  select your Country!",
                'Address.State.SubnationalIsoCode': "Please  select your State!",
                'Address.PostalCode': {
                    required: "Please enter your Postal Code!",
                    minlength: "Your Postal Code must be 5 numbers!",
                    maxlength: "Your Postal Code must be 5 numbers!",
                    digits: "Your Postal Code must be 5 numbers!"
                }
            }
        });

    });
</script>

@using (Html.BeginForm(Model.Step.ToString(), "Provision", FormMethod.Post, new Dictionary<string, object> { { "id", "locationSetup" } }))

<table width="100%" id="locInfo">
            <colgroup>
                <col width="30%" />
                <col />
            </colgroup>
            <tr>
                <th><label>@AddressResource.COUNTRY_LABEL_TEXT:</label> <span class="redtext">(Required)</span></th>
                <td>
                   @* @Html.HiddenFor(m => m.Address.State.Country.CountryIsoCode)*@
                   @Html.DropDownListFor(m => m.Address.State.Country.CountryIsoCode, ProvisioningHubProxy.GetCountriesList(),
                                htmlAttributes: new { @id = "Countries", @name = "Countries" })
                </td>
            </tr>
            <tr>
                <th> <label>@AddressResource.STATES_LABEL_TEXT:</label><span class="redtext">(Required)</span></th>
                <td> @Html.DropDownListFor(m => m.Address.State.SubnationalIsoCode, ProvisioningHubProxy.GetStatesList(),
                                htmlAttributes: new { @id = "States", @name = "States" })</td>
            </tr>
            <tr>
                <th><label>@AddressResource.CITY_LABEL_LABEL_TEXT:</label><span class="redtext">(Required)</span></th>
                <td> @Html.TextBoxFor(m => m.Address.City, htmlAttributes: new { @name = "City", @id = "City" })</td>
            </tr>
            <tr>
                <th> <label>@AddressResource.STREET_NAME_LABEL_TEXT:</label><span class="redtext">(Required)</span></th>
                <td>@Html.TextBoxFor(m => m.Address.AddressStreet, htmlAttributes: new { @name = "StreetName", @id = "StreetName" })</td>
            </tr>
            <tr>
                <th><label>@AddressResource.US_POSTAL_CODE_LABEL_TEXT:</label><span class="redtext">(Required)</span></th>
                <td>@Html.TextBoxFor(m => m.Address.PostalCode, htmlAttributes: new { @name = "ZipCode", @id = "ZipCode", @required = "required" })</td>
            </tr>
        </table>

}

}

Please suggest.

请建议。

回答by Brad Christie

Add a custom validator:

添加自定义验证器:

jQuery.validator.addMethod("zipcode", function(value, element) {
  return this.optional(element) || /^\d{5}(?:-\d{4})?$/.test(value);
}, "Please provide a valid zipcode.");

_If you want to accept spaces1between zipcode, use /^\d{5}(?:[\s-]\d{4})?$/for the pattern instead.

_如果您想在邮政编码之间接受空格1,请改用/^\d{5}(?:[\s-]\d{4})?$/模式。

then specify it in your options:

然后在您的选项中指定它:

rules: {
  ...
  'Address.PostalCode': {
    ...
    zipcode: true,
    ...
  },
  ...
}

Note that the extension library additional-methods.jshas a zipcodeUSvalidator as well (but unless you're using any of the other ones it may not make sense to include it).

请注意,扩展库additional-methods.js也有一个zipcodeUS验证器(但除非您使用其他任何一个,否则包含它可能没有意义)。



1According to the spec, properly formatted zip codes consist of five (5) numbers or five (5) numbers follower by a hyphen (-) and four (4) additional numbers. A space shouldn't technicallybe acceptable, but I'll provide the pattern regardless.

1根据规范,格式正确的邮政编码由五 (5) 个数字或五 (5) 个数字后跟一个连字符 (-) 和四 (4) 个附加数字组成。从技术上讲,空间不应该是可以接受的,但无论如何我都会提供模式。

回答by Sparky

Simply include the additional-methods.jsfileand use the zipcodeUSrule.

只是包括additional-methods.js文件和使用zipcodeUS规则。

$("#locationSetup").validate({
    rules: {
        // rules,
        'Address.PostalCode': {
            required: true,
            zipcodeUS: true // <-- use it like this
        }
    },
....

If you don't want to include the additional-methods.jsfile, you can copy the following method into your code...

如果您不想包含该additional-methods.js文件,可以将以下方法复制到您的代码中...

jQuery.validator.addMethod("zipcodeUS", function(value, element) {
    return this.optional(element) || /\d{5}-\d{4}$|^\d{5}$/.test(value)
}, "The specified US ZIP Code is invalid");

回答by Blago

You can define a custom validator:

您可以定义自定义验证器:

jQuery.validator.addMethod('zipcode', function(value, element) {
  return this.optional(element) || !!value.trim().match(/^\d{5}(?:[-\s]\d{4})?$/);
}, 'Invalid zip code');

Then use it like this

然后像这样使用它

<input class="zipcode"/>

回答by Paul Smith

Zip code validation routines are provide in additional-methods.js but I would question why you ask for country information if you are going to invalidate the form for any country other than the US? Please remember that only about 5% of the worlds population uses a US zipcode. I would recommend you make you postcode validation routines dependent on the country actually selected by the user.

邮政编码验证例程在 additional-methods.js 中提供,但如果您要使美国以外的任何国家/地区的表单无效,我会质疑为什么要询问国家/地区信息?请记住,世界上只有大约 5% 的人口使用美国邮政编码。我建议您根据用户实际选择的国家/地区设置邮政编码验证例程。