jQuery validation plugin: accept only US, Canada and Mexic zip code?

ぐ巨炮叔叔 提交于 2020-01-21 08:56:28

问题


I'd like to use jQuery validation plugin to validate a zip code field that accept only US, Canadian or Mexican zip code format, but there doesn't seem to be a defined rule for it. I've searched Google but I've found nothing useful.

I have to accept only these zip code formats:

US: 99999-9999 or 99999 Canada: A9A 9A9 MX: 99999

Appreciate your help.


回答1:


Look inside the additional-methods.js file for the various zip code rules. You can copy and tweak them as you see fit.

jQuery.validator.addMethod("ziprange", function(value, element) {
    return this.optional(element) || /^90[2-5]\d\{2\}-\d{4}$/.test(value);
}, "Your ZIP-code must be in the range 902xx-xxxx to 905-xx-xxxx");

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");


来源:https://stackoverflow.com/questions/15794913/jquery-validation-plugin-accept-only-us-canada-and-mexic-zip-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!