18

I am using the jQuery Validation plugin for validating my form.

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.

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.

Sparky
  • 98,165
  • 25
  • 199
  • 285
UID
  • 4,434
  • 11
  • 45
  • 75
  • possible duplicate of [jQuery validation plugin: accept only US, Canada and Mexic zip code?](http://stackoverflow.com/questions/15794913/jquery-validation-plugin-accept-only-us-canada-and-mexic-zip-code) – Blazemonger Sep 25 '13 at 18:07
  • 5
    There's already a rule called `zipcodeUS` inside [the `additional-methods.js` file](http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/additional-methods.js). – Sparky Sep 25 '13 at 22:10

4 Answers4

31

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 spaces1 between zipcode, use /^\d{5}(?:[\s-]\d{4})?$/ for the pattern instead.

then specify it in your options:

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

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


1 According 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 technically be acceptable, but I'll provide the pattern regardless.

Brad Christie
  • 100,477
  • 16
  • 156
  • 200
16

Simply include the additional-methods.js file and use the zipcodeUS rule.

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

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

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");
Sparky
  • 98,165
  • 25
  • 199
  • 285
  • ,if I try this it gives me error TypeError: jQuery.validator is undefined. Can you tell me what actually I am missing here. – ehp Apr 03 '14 at 15:41
  • @ehp, The error is telling you that the `validator` is not defined. It simply means you did not properly include the jQuery Validation plugin. – Sparky Apr 03 '14 at 16:05
  • Just a note. If you do use the additional-methods.js make sure to get the version that corresponds with the version of the validation plugin you are using. The file here is 1.11.1 and the newest at this time as 1.12.0. The 1.11 was giving errors with 1.12. – Tim Ramsey Jun 08 '14 at 22:54
  • 1
    @TimRamsey, all that should really go without saying, since newer plugin versions will always be forthcoming. Anyway, the latest at the time this answer was written was 1.11.1 and I must have scores of answers linked to the latest at that time. – Sparky Jun 09 '14 at 01:10
3

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"/>
Blago
  • 4,697
  • 2
  • 34
  • 29
1

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.

Paul Smith
  • 454
  • 6
  • 11