How to validate US ZIP code using jQuery Validation plugin

前端 未结 4 1094
予麋鹿
予麋鹿 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: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

    
    

提交回复
热议问题