My Client-side life
September 16, 2005 – 11:32 pmAh, the joys of Javascript. I’ve been swimming in some nifty client-side code for the last two weeks or so (Ajax and triggers and the yellow-fade technique, oh my). I’ve doing some heavy lifting with PHP5 (hurray for encapsulation), too, but the thing that I’m happiest about recently has been client-side form validation.
I’ve always been an advocate of redundant form validation - catch errors early and often to provide the best possible user experience. On my current project, I’m using three different stages of validation.
Certain fields require unique entries; these make an Ajax call when they lose focus to check if the entered data already exists in the system, and if it does they present the error with some suggested alternatives. That’s my pre-submit validation.
My post-submit validation is standard server-side stuff - these are the expected fields, did they show up? Is what’s in ‘em expected? If not, drop the client back onto the form, highlight the bad fields, and provide error messages as to what went wrong.
The fun part is the on-submit validation. Any field can have one of several custom attributes - required, pattern, confirms, and errormessage being the most common. When a form is submitted, I’m using Javascript to loop through the inputs, selects, and textareas and checking for those attributes. If an input has required=”true” and lacks a value, the field is highlighted and an error message (specified in the errormessage attribute, or a default one with the field ID) is added to a message buffer. If a field has a pattern attribute, its contents are matched against a regular expression with the pattern (and I’ve added aliases for the common patterns - email, URL, etc.). If a field has a confirms attribute, the Javascript makes sure that the value in the confirming field matches the value in the field whose ID appears in the attribute - handy for all those ‘retype your password’ fields.
I’m so high on this method because it’s immediately graspable by maintenance staff (even non-technical staff), it’s quick, and it doesn’t do too much violence to the notion of semantic coding. The only downsides that I can see are that it fails when Javascript is off (but the server-side validation catches that), and that it doesn’t validate against the current XHTML DTDs. Of course, I could always write my own DTD to add the new attributes, but even without doing that I think this is a model of the right way to employ Javascript.


3 Responses to “My Client-side life”
Nice coding! I think redundancy is key. I don’t know if users appreciate form validation. I do. I love being told that I messed up in a cool way.
By ShoreTurtle on Sep 17, 2005
and what about your running?
By aprilanne on Sep 18, 2005
Hello?!? Are you still there?
I hope things are going well.
By aprilanne on Oct 17, 2005