Question

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.

Was it helpful?

Solution

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");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top