Monday, March 5, 2012

Client Side Form Validation - jQuery Validation plugin

Client side validation and server side validation are both important and should go side by side.

Client Side validation - valuable for quick check of simple input mistakes, very fast, increases interactivity, user doesn't need to wait after each submit, saves server load and there's no unnecessary traffic, but it's not a replacement for a server side validation.

Server side validation - still needed as a "second line of defence" (user can easily disable or change JavaScript and break the client side validation) and for more complicated validations.

One of the options for a client side validation is jQuery Validation plugin which makes things really simple. This plugin contains a set of validation methods (e.g. email/url validation) and provides API so you can write your own methods.

All you need is a single line of code to select the form and apply validation plugin:

<script type="text/javascript">

And some metadata on the form:
- class="required valid" and minlength="2" for name input
- class="required valid" and type="email" for email input

<form id="simpleForm" method="get" action="" novalidate="novalidate">
   <label for="name">Name (minimum 2 characters) *</label>
   <input id="name" name="name" class="required valid" minlength="2"><label for="cname" generated="true" class="error" style="display: none; ">Please enter at least 2 characters.</label>
   <label for="email">E-Mail *</label>
   <input id="email" type="email" name="email" class="required valid"><label for="cemail" generated="true" class="error" style="display: none; ">Please enter a valid email address.</label>
   <input class="submit" type="submit" value="Submit">

Some of the most used input field attributes are:

type="email", "url", "date", "number", "digits", "creditcard", "phoneUS"
min, max, maxlength, minlength="5"

More complex examples and explanations can be found on:
Documentation for jQuery Validation plugin:
If you want to read more about Server Side Validation using Spring Validator interface there's another post explaining how it can be done.

No comments:

Post a Comment