How to validate US ZIP code using jQuery Validation plugin

前端 未结 4 1093
予麋鹿
予麋鹿 2020-12-09 04:51

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-678         


        
相关标签:
4条回答
  • 2020-12-09 05:02

    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.

    0 讨论(0)
  • 2020-12-09 05:03

    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.

    0 讨论(0)
  • 2020-12-09 05:05

    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");
    
    0 讨论(0)
  • 2020-12-09 05:15

    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"/>
    
    0 讨论(0)
提交回复
热议问题