2
$\begingroup$

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.

$\endgroup$
2
  • $\begingroup$ Did you check the website? bassistance.de/jquery-plugins/jquery-plugin-validation $\endgroup$ Commented Apr 3, 2013 at 18:30
  • $\begingroup$ Yes, but I need to accept only these 3 formats above. See my comment below. It's working for me. Thanks. $\endgroup$ Commented Apr 4, 2013 at 0:49

1 Answer 1

4
$\begingroup$

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");
$\endgroup$
Sign up to request clarification or add additional context in comments.

3 Comments

Good point to start with. I didn't see it in the additional methods, especially for zipcodeUS. Thanks.
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]$/
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.