Menu

In the last post I covered the basics of getting up and running with the jQuery validation plugin. In this post I am going to cover the steps needed to move the error messages away from the input fields they apply to and position them instead in a single location.

The effect we’re aiming for is shown in the screenshot below:

Getting Started

The first step is to create our form and add our jQuery validation rules to it. For the purpose of this example, I have re-used the majority of the code from the previous post.

The “style.css” file has also been modified slightly and the styles specific to the last post have been removed. Our “style.css” file should now contain the following:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

body{

font-family:Georgia,"Times New Roman",Times,Serif;

padding:1em;

background-color:#F2F2F2;

}

h2{

border-bottom:1pxsolid#DDD;

}

div{

background-color:#FFF;

border:1pxsolid#A8A8A8;

padding:0.5em;

margin-bottom:1em;

}

input{

font-family:Georgia,"Times New Roman",Times,Serif;

}

label{

width:10em;

float:left;

}

p{

clear:both;

}

If you were to run the page as is, you will see that the validation is performed correctly, however the labels aren’t quite positioned correctly (don’t worry about this for now as we’re going to be moving them).

Creating the “Error Container”

The next step to moving the error messages is to create the section on the page that we want to move the error messages to!

As you can see from the screenshot above, we want to display a generic bit of text to our users, informing them that they have errors on the page, along with a listing of what those errors are. To do this, we just need to create a div above our form that contains the text and an empty list.

1

2

3

4

<div id="errorContainer">

<p>Please correct the following errors andtryagain:</p>

<ul/>

</div>

We also want to add a couple of additional CSS styles to the page to make the error container stand out.

1

2

3

4

5

6

7

8

9

10

11

12

#errorContainer {

display:none;

overflow:auto;

background-color:#FFDDDD;

border:1pxsolid#FF2323;

padding-top:0;

}

#errorContainer label {

float:none;

width:auto;

}

As you can see from the CSS above, we initially hide the error container div. The jQuery validation plugin will take care of displaying this automatically if our form does not pass the validation rules we have setup.

Modifying the JavaScript

Now that we have everything in place, we need to pass some additional information into the validation plugin to tell it how we want the error messages displayed and where we want them to appear.

errorContainer

The first bit of information we need to supply is the element that is going to contain our error messages. This element will automatically be shown by the validation plugin if the form does not validate according to the rules we have setup. Note that this is not the actual element that the error messages are appended to.

errorLabelContainer

The error label container is the element that we want the error messages appended to. In our example, we want the validation messages to appear in a list, so we need to supply the selector to the list element.

wrapper

The final option we need to specify is how the error messages should be wrapped up. As we are displaying the messages in a list, we need to ensure that the error message labels are wrapped as list items.

If we left this option out, the validation plugin would append label elements into the element we specify as the error label container (which would result in an invalid list in our case).

Improvements

With all of this in place you can now go ahead try out the page and the error messages should now appear at the top of the page!

One slight improvement we can make at this stage is to also highlight the input fields that are invalid. As we’ve moved the error messages to the top of the page, it can be hard to see at a glance which fields are invalid. Highlighting the input elements gives us the visual indication that something is wrong, whilst at the same time we can keep all our error messages displayed in a single location at the top of the form.

To add the highlighting, we just need to add the following snippet of CSS:

The jQuery validation plugin is a comprehensive plugin for adding validation capabilities to your forms. The plugin comes with a host of common validation functions already built in and also offers extensibility points to add in your own custom validation functions. This post will outline the minimum you need to do to get up and running with the plugin. Further posts will explore some of the more advanced scenarios that the validation plugin can handle.

For the purpose of this post we will be building a simple web page that contains two forms. One form will be validated by decorating the fields we want to validate with additional classes and attributes. The second form will be validated by specifying the validation rules with JavaScript.

Class and Attribute Based Form Validation

The first step is to start with a simple HTML page and add references to jQuery and the jQuery validation plugin.

I have also added a basic style sheet that contains a couple of basic styles (we will come to the jQuery validation specific ones a little later on).

The next step is to add a basic form that we can apply our validation classes and attributes to.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

<div>

<h2>ClassandAttribute Based Form Validation</h2>

<form id="classBasedValidation">

<p>

<label for="firstName">First Name:</label>

<input id="firstName"name="firstName"></input>

</p>

<p>

<label for="lastName">Last Name:</label>

<input id="lastName"name="lastName"></input>

</p>

<p>

<label for="age">Age:</label>

<input id="age"name="age"></input>

</p>

<p>

<input type="submit"value="Submit"/>

</p>

</form>

</div>

One point to note with the input elements above is that they all have name attributes. If these aren’t specified on all of the fields you are validating within your form then you will find that the validation plugin will only validate the first field.

Now that the form is in place, we will be applying the following validation rules to our form:

In this example we will be making use of the “required”, “min” and “max” validation functions. There seems to be a bug with the range function when specifying the values on an attribute, so we will use min and max to achieve the same result.

Now that we know which functions we are going to use, we can go ahead and decorate our input elements.

1

2

3

<input id="firstName"name="firstName"class="required"></input>

<input id="lastName"name="lastName"class="required"></input>

<input id="age"name="age"class="required"min="18"max="70"></input>

As you can see in the code above, validation functions that don’t take any arguments can be specified as classes on the element. Validation functions that do take arguments are specified with the name of the function as the attribute, and the argument you want to pass into the function as the value.

Now everything is in place, the final step is to hook up the validation plugin to the form!

Add the following script to the bottom of the page (below the script reference to the validation plugin).

1

2

3

4

5

6

7

<script type="text/javascript">

$(function(){

$('#classBasedValidation').validate();

});

</script>

If you now run the web page and try to submit the form as it is (without filling any of the fields in), you should now see the validation warnings appear next to the input boxes.

The validation plugin will add an “error” class to any input fields that are invalid and to the labels it generates (for displaying the validation message). This class can be targeted in CSS to style the validation message in a different colour, for example.

JavaScript Based Form Validation

Next we will go ahead and perform the same validation on a different form, however this time we will add the validation rules via JavaScript.

Add the following form to the page (below the example that we created above).

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

<div>

<h2>JavaScript Based Form Validation</h2>

<form id="jsBasedValidation">

<p>

<label for="jsFirstName">First Name:</label>

<input id="jsFirstName"name="firstName"></input>

</p>

<p>

<label for="jslastName">Last Name:</label>

<input id="jslastName"name="lastName"></input>

</p>

<p>

<label for="jsAge">Age:</label>

<input id="jsAge"name="age"></input>

</p>

<p>

<input type="submit"value="Submit"/>

</p>

</form>

</div>

We will use the same validation rules for these fields as we did in the example above, however for this example, we will go one step further and customise the validation warning messages.

In order to specify which validation rules apply to which fields, we need to pass this information into the plugin when we initialise it.

As you can see, the syntax for specifying which validation rules to apply is quite straight forward. The name of the input element we want to target forms the “key” part of the JSON key/value pair, and the “value” part is the name of the validation function that we want to apply to this element. If the validation function takes an argument, or we want to apply multiple validation functions, we specify this with another JSON object with the key as the name of the validationfunction and the value as the argument we want to pass in (we have done this for the age field).

Custom validation messages are also specified using a similar syntax, the key is the name of the element we are targeting and the value is the message we want to use. If the element has more than one validation function attached to it, then we can pass another JSON object which has the name of the validation function as the key and the validation message as the value.

If you try and submit this form without filling in any values then you should see the same validation checks being performed as before but now we have our custom validation messages displayed.