jQuery validator plugin – custom method for postal code validation
April 20th, 2008
Comments6
With my previous post on jQuery, I thought I would share a simple add-on method for the jQuery Validation plugin. If you are from Canada or writing a Canadian validation form with a postal code field you can use this. Just add the code below in your rules script.
// Addon method for validating postal codes. Valid // formats are (X1X 1X1) or (X1X1X1) or (X1X-1X1). $.validator.addMethod("postalCode", function(value) { return value.match(/^[a-zA-Z][0-9][a-zA-Z](-| )?[0-9][a-zA-Z][0-9]$/); }, 'Please enter a valid postal code');
Then you can use the rules required:true and postalCode:true in your rule set.
Daniil June 2, 2009 at 10:53 am
Thank you, exactly what I needed!
Paul Warren April 16, 2011 at 3:21 am
Forgive me, but for some reason, when I use this function, the “Please enter a valid postal code” message does not disappear when a valid zip is entered. any idea what could cause this?
Ian Hoar April 16, 2011 at 11:25 am
Hi Paul, I would have to see the code to know why. Do you have both jQuery and the Validator plugin linked? Does it work in any browser, IE is very picky about commas in jQuery.
rockstar June 28, 2011 at 10:51 am
Hi Ian,
How to make it in uppercase after it validates?
Ian July 1, 2011 at 8:03 pm
Hi rockstar, take a look at the JavaScript function toUpperCase(), this should do the trick.
http://www.w3schools.com/jsref/jsref_toUpperCase.asp
Daniel January 31, 2012 at 10:57 am
Any idea why this is not validating with a space in the middle, i.e. A1A 1A1?
Thanks.