Validating user input on the client definitely has its advantages. It not only avoids unnecessary round trips to the server but it can also drastically improve the user experience. When I think about client side validation I think about jQuery. If you are familiar with jQuery, then you know that there are a ton a plug-ins available. Just like an Apple IPod has “an app for that”, jQuery has a “plugin for that”. Anyway, after a quick search I discovered the jQuery Validation plugin.
There are a bunch of different class names that the plugin will honor. The most basic class name is required. However in addition to checking if a field is required you can also perform pattern matching. For example my form has an email field. When someone fills out this field I not only want it to be required, but I also want to make sure that a valid email address is entered. In order to achieve this I use the class name required email. Similar validators are available for website addresses, dates, credit card numbers and more. See the documentation page for the complete list.
Here is a screenshot of my comment form:
Here is the HTML markup for my form. Notice the class names used in each of the input fields. From the html you can deduce that the full name is required. The Email is required and must be a valid address. The website field is optional but if text is entered is must be a valid URL. Finally, the comment field is required:
<form id="comment_form" action="#">
<label>Full Name *</label>
<input type="hidden" id="postID" name="postID" value='<%=Model.ID %>' />
<input type="text" id="author" name="author" class="required" value="" size="40"/>
<input type="text" id="email" name="email" class="required email" value="" size="40"/>
<input type="text" id="website" name="website" class="url" size="40" />
<textarea id="comments" name="comments" rows="8" cols="60" class="required"></textarea>
<input type="submit" id="btnSaveComment" value="Save Comment" class="submit" />
<img id="ajax_loading" src="/Content/images/ajax_loading.gif" alt="loading" />
To wire up the plug-in you only need one line of code in the document.ready event:
var validator = $("#comment_form").validate();
Client side validation is a great way to enhance user experience. However, keep in mind that client side and server side validation can be used together. As always, pick the right tool for the job. For example, if you are working with mobile devices that have limited capabilities it may make more sense to use server-side validation.