Posts Tagged ‘javascript’

jQuery Zip/Postal Code Validation Method

September 1st, 2009

For those of you who may be familiar with Jörn Zaefferer’s jQuery Validation plugin, I’ve written a method for validating zip/postal code fields, which was not included in the plugin.

To start validating zip/postal code fields, include this code somewhere after you’ve included the plugin:


jQuery.validator.addMethod("postalcode", function(postalcode, element) {
	return this.optional(element) || postalcode.match(/(^\d{5}(-\d{4})?$)|(^[ABCEGHJKLMNPRSTVXYabceghjklmnpstvxy]{1}\d{1}[A-Za-z]{1} ?\d{1}[A-Za-z]{1}\d{1})$/);
}, "Please specify a valid postal/zip code");

Now you can add postalcode to your validation rules like so:


$("#myform").validate({
	rules: {
		postalcode: {
			postalcode: true
		}
	}
});

Note: this will accept both Canadian postal codes (with or without a space) and U.S. zip codes. Enjoy!

Inline Validation: Don’t get trigger happy!

August 31st, 2009

Javascript is great for providing timely feedback to users while they are filling out forms. Seeing validation messages inline while a form is being filled out allows the user to correct errors before submitting the form, which saves time and generally offers a better experience.

However, it’s important to note that validation errors should only be shown at the appropriate time. Today, I was adding a new contact in Gmail and I noticed something odd when I was typing in the contact’s email address. The background of the email field immediately went bright red as soon as I had typed the first letter.

Gmail email address validation error

Obviously, this caused some confusion. I quickly realized that I was being notified that the field did not contain a valid email address (because I was in the middle of typing it).

The point I’m driving at here is that you shouldn’t tell your users they’ve done something wrong until they’ve actually done it. Field validation is usually best left until the user has moved on to another field or performed another action which signifies that they believe they’ve completed the field in question.

Note: One exception to this general rule of thumb, is when a user enters an invalid character in a field (eg. a letter in a phone number field). In that case, it may make sense to let them know right away.

Update: Luke Wroblewski just wrote a great article on inline validation on A List Apart. The portion on testing when to show inline validation
 bears particular relevance to this post.