Friday, February 17, 2012

Only Writing One Set of Form Validation Code

Form validation is an important part of Web development. It provides the user feedback when they make a mistake or omit information. And it protects the integrity of the application data.

In the past I have written 2 sets of form validation: 1 client-side and 1 server-side. Server side form validation is essential. Client-side validation wasn't always necessary in the past, but provided a better user experience. However, as more and more dynamic client-side content is being generated, it is becoming more essential and users are not as tolerant of "press the back button to correct your errors".

So instead of writing 2 sets of validation code (one in JavaScript and one in ColdFusion), I now levy the power of AJAX to only write one set of form validation code.

The way it works is to submit the form data to the server first via AJAX. The server side code then generates any and all error messages based on the form data. If there are errors, it sends the error messages back to the browser as JSON array. If there are no errors, then it submits the form to the client.

So what if the user has JavaScript disabled (does anybody do that anymore?) or somehow JavaScript is bypassed? The same error messages are then presented back to the user regardless. Here's some sample code to make more sense of it.

First our HTML form:

Next we add the JavaScript to handle the AJAX check and form submission:

And finally the client-side code:

0 comments:

Post a Comment

 
Blogger Templates