Javascript-based web form validation done correctly

Wednesday, 2 Feb 2005 [Saturday, 5 Feb 2005]

Blake Scarbrough posted some Javascript snippets he uses a lot. Among them is a short piece of code to check whether a form has been filled out correctly. The way it’s written, it will present an error dialog to user if he hits the submit button of the form before he has finished filling out the form.

This is a very common approach, mainly because it’s so easy to implement: just drop an onClick handler on the submit button and away you go. It doesn’t require any markup diddling nor dynamic HTML toil.

As with many things programmer-friendly, it’s not exactly ideal an ideal interface, though. A better idea is to have the submit button disabled by default (by some onLoad code, not in the markup, because otherwise you’re making Javascript a requirement for using the form), and have a visual indication for required fields. This could be a faint red highlight on the field, a red asterisk by the field label, a “required” caption, or whatever you prefer. As the user fills out the fields, an onChange handler on each field checks the entered value and removes the respective visual indication if it finds the value satisfactory. If it detects that all obligations are met, it also enables the submit button so the user can send the form.

Why is this more usable? Doing things this way also provides the user with realtime feedback on whether he has satisfied the conditions, and also makes it impossible to make an erroneous interaction (here: submitting a partially filled form) in the first place, instead of interjecting when it has already happened. Think of it as installing a rail and direction signs on a trail, vs giving visitors no hint as to where the trail is and leaving them to stumble into “no trespassing” signs.

Some example code can be found in the Simple Tricks for More Usable Forms article on SitePoint.