Web design elements: form validation with jQuery
In the past lessons, we looked at how to structure a form and the basic choices to be made. However, we overlooked something important: errors. Have you ever filled in a long form and, only after submitting, come to realize that you made a mistake? Well, let’s look at how JavaScript (and in particular jQuery) can help!
We’ve all been there: you fill in a form, somehow decipher the captcha, accept the user agreement and submit. Five seconds. Username is unavailable. Redo the entire form. Captcha. User agreement. Submit. Five seconds. Passwords don’t match. Redo. Captcha. User agreement. Submit.
The problem shown in this example is the delay between one submission and the next, due to the interaction between the client (submitting the form) and the server (validation and return result). The user’s positive-experience suffers quite a bit (as does their patience), but how can we fix this? One possible solution is to use JavaScript to add a client-side validation to the server-side validation. Please note that I wrote to add and not to substitute: server-side validation is of prime importance, and must always be present!
The main advantage of client-side validation is that it happens in real time, therefore allowing for immediate correction of any errors.
Reinventing the wheel or just reusing it?
Even though it’s relatively simple to create a form validation system from scratch using jQuery, there are various plugins already out there, created by those who have already remedied this problem. There are several advantages to using these plugins:
- You don’t have to reinvent the wheel.
- They offer well-tested functionality for all main browsers.
- You have more time to concentrate on other problems.
Having said this, if you have particular needs to meet, nothing stops you from creating something more appropriate. The form that we’ll use is similar to the one created in the previous lesson, to which we added fields for a username and password.
To validate our example form, we’ll use the validation plugin from the jQuery repository. This is one of the oldest plugins (the documentation refers to July 2006) and in time it has acquired many functions that make it very versatile.
Once we’ve downloaded the archive and extracted the content, we’ll copy the file jquery.validate.js to our working directory. Naturally, we’ll also need the latest version of jQuery and a blank file to work on. Let’s link everything together in our XHTML file:
... <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="jquery.validate.js"></script> <script type="text/javascript" src="validateYIW.js"></script> ...
Methods and Rules
The validation plugin is based on two basic concepts: methods and rules. Methods represent the validation logic for our fields: for example, the method email verifies that the text inserted actually represents an e-mail address. There are twentysome methods that come with the plugin: the most important is certainly the method required which allows you to specify if a field is required or not. Here is the complete documentation along with some examples.
The rules connect the methods to various fields, therefore allowing for the validation of the form. As usual, an example is worth a thousand words. So let’s open the file validateYIW.js with the editor:
jQuery(document).ready(function($){
//Validation rules
$("#formYIW").validate({
rules: {
firstname: {
required:true,
minlength:2
},
lastname: {
required: true,
minlength:2
},
email: {
required: true,
email: true
},
username: {
required: true,
minlength: 2,
maxlength: 20
},
password: {
required: true
},
passwordrpt: {
equalTo: "#password"
}
},
...
The plugin is activated by the function .validate, which is applied to the selected form by using an ID. Inside of the function we’ll insert the rules element which contains all the rules for our form, field by field. Each rule is comprised of the attributed field name, to which we can then apply methods and specify values. Let’s analyze them one at a time:
- required: if setup as true, it makes the field required.
- minlength: determines the minimum number of characters permitted in a field.
- maxlength: determines the maximum number of characters permitted in a field.
- email: if setup as true, it verifies that the text inserted is a valid e-mail address.
- equalTo: verifies if the text introduced in a field is the same as in the field it is compared to.
As you can see validation is already functional: once you submit the form the plugin adds a message next to each field containing an error. By default these messages are grouped in a label element associated by the class “error”. To highlight them, I increased the size of the text and colored them red:
#formYIW label.error{
color:#9E142E;
float:none;
font-size:105%;
font-weight:bold;
margin-left:.5em;
}
So, you’ll have noticed that all the messages are in English. Even though the plugin offers a localization file in Italian, I find it’s too generic. It’s better to specify a personalized message for each error type: this is easily done using the messages element:
...
//Error messages
messages:{
firstname: {
required: "Please provide your first name",
minlength: "First name must contain at least 2 letters"
},
lastname: {
required: "Please provide your last name",
minlength: "Last name must contain at least 2 letters"
},
email: {
required: "Please provide your e-mail address",
email: "Please provide a valid e-mail address"
},
username: {
required: "Please specify a username",
minlength: "Username must contain at least 2 characters",
maxlength: "Username cannot contain more than 20 characters"
},
password: {
required: "Please provide a password"
},
passwordrpt: {
equalTo: "Passwords must match"
}
},
...
Following the same structure of rules, I specified a message for each error, in order to guide the user toward error resolution. The resulting form is already acceptable: let’s see how we can make it even better.
It would be useful to highlight the fields that contain errors. To do so we can use the highlight and unhighlight elements that allow us to specify actions to take in the presence or absence of errors, respectively. The syntax for both is as follows:
...
highlight: function(element, errorClass){
//action to take in the event of an error
},
unhighlight: function(element, errorClass){
//action to take when error is resolved
},
...
As you can see, both elements need a function in which to specify two things:
- element, represents the form element with errors
- errorClass, represents the name of the error class (by default it’s “error”)
Therefore we can think about adding the class “error” to the li elements that have various input elements and then apply graphic feedback using CSS.
...
//action to take in the event of an error
highlight: function(element, errorClass){
$(element).parent("li").addClass(errorClass);
},
//action to take when error is resolved
unhighlight: function(element, errorClass){
$(element).parent("li").removeClass(errorClass);
}
Seeing as the element li contains the input element, let’s use the jQuery parent function to select it, and making use of this connection, we’ll also add the error class. Now the only thing left is to apply some CSS rules, so we can better highlight the errors:
#formYIW li.error{
background-color:#FFCCFF;
color:#9E142E;
}
The final result is more than satisfactory.
The validation plugin allows for a large margin of improvement: for example, you could add a box showing the number of errors above the form, in order to provide better graphic feedback.
Conclusion and things to consider
In this article we looked at how to use jQuery to improve the user-friendliness of forms, starting off with simple XHTML+CSS. And with that we’ll close the series on forms. Next we’ll see how to create database links using PHP.
I’d like to leave you with something to think about: forms, even considering all the graphic embellishments and JavaScript improvements, haven’t really evolved much. We still fill them in field by field! Do you think that some kind of present or future technology or approach, could limit the use of forms, predominant as they are in our daily life on the web?
- Forms: basic elements
- Forms: structure and appearance
- Forms: jQuery and things to consider
*****************************************
L'immagine principale dell'articolo è stata fornita da @Fotolia






thank tou very much I going to used it for my academic portfolio. »
Dear Yourinspirationweb, Cool Post, Life is full of appointments. Some are important ones and... »
What's the original font of the wordpress login called? The one you write in... »
Simple but gorgeous design. It's in a class of its own. »
In the portfolio only shows 10 thumbnails, and published 14 ... how do I... »
hi... can anyone tell how to implement 3rd level drop down menu? »