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

1

2

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.

Stillman answered 3/4, 2013 at 18:16 Comment(2)
Did you check the website? bassistance.de/jquery-plugins/jquery-plugin-validationDemilune
Yes, but I need to accept only these 3 formats above. See my comment below. It's working for me. Thanks.Stillman
D
4

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");
Demilune answered 3/4, 2013 at 18:28 Comment(3)
Good point to start with. I didn't see it in the additional methods, especially for zipcodeUS. Thanks.Stillman
OK, the last regex I come up with for validating US, CA and MX zip codes is: /\d{5}-\d{4}$|^\d{5}$|^[a-zA-Z][0-9][a-zA-Z](| )?[0-9][a-zA-Z][0-9]$/Stillman
@doub1ejack Not really important to me but thanks for pointing out the LDU 9Z0. It's also matching H0H0H0 which is not a valid postal code but the goal is to show the user that we are validating the postal code not to be exhaustive or go crazy about.Stillman

© 2022 - 2024 — McMap. All rights reserved.