You are on page 1of 7

Jquery Reference settings

Now the form is prepared for client side validation. You need to download the JQuery library reference in order to carry on the JQuery validation (www.jquery.org). After you download the reference, set it as shown below.
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>

In HTML coding it is better to place all your .JS files in a separate folder. Similarly, another JS file called valitioninput.js should be created and saved in the same file. This file should contain all the custom validation codes.
<script type="text/javascript" src="js/validationinput.js"></script>

Building the jquery validation code


You need to add page ready() event before you begin any JQuery coding. It should be placed as shown below.
$(document).ready(function() { //All your code will wirte inside here.

}); After the page loads in the browser, the code snippets for events and others will be inside the above method and will start functioning. In Javascript coding also we need to declare variables to read and store input values same as in other programming languages.

Read required inputs


The selectors that are going to be used should be identified so as to read values from HTML Form controls. Choosing a selector is helpful to read, assign or trigger events of HTML controls. CSS class, control ID and the control TAG name are the three types of selectors to read HTML controls. Here to select each element, Ive used pseudo ID. Next we need to decide the required values. In this situation were going to validate only one text box. Therefore the text box value and its span tag to display the error message should be coded. var name = $("#txtname"); //textbox you are going to validate var nameInfo = $("#infotext"); //to display error message These are the first two lines of code which are inside the Document Ready Event. These two variables act globally for all other functions within the ready event.

Events to be validated
Now lets think about the events needed to validate this name text box. At this time you know that the submit event of the Form should be handled. Why? We have to perform validation for input controls before it is submitted. For navigation through text input fields sometimes users may use either TAB or arrow keys. In such a situation the system should validate the input at that moment.

Here, the input control should be handled onBlur event. If the user selects the mouse instead of the TAB or arrow keys, onKeyDown event should be handled.

Submit event
The below code shows how to handle form submit button action.
$(#form1).submit(function() { // validation begin before submit });

Here Ive used the pseudo ID to select the HTML form. Once it is selected we can use the submit function. Submit function is equal to onSubmit event of the html Form control. This event will be generated when the user clicks on submit button. Once it is generated client side validations for input text box should perform. Since we need to perform the same validation for the other two events as well, the best solution will be to create separate function to perform validation to text box. We can generalize the validation of text box into one central location, which lead to easy maintenance of code by using this approach.Your submit event handler code will be as follows;
//first validation on form submit form.submit(function() { // validation begin before submit if (validateName()) { return true; } else { return false; } });

If the validateName returns true form, it will be submitted else display client side error messages

Blur event
Same validate function can be called inside the blur event handler. You can add below code to create blur event validate;
name.blur(validateName);

KeyDown event
As shown above add below code to handle keyup;
name.keyup(validateName);

Building validation function

Inside event handler it is needed to identify what validations need to check. For a given text field validation you may need to check for empty entries, unwanted characters such as numbers (eg. You may not input numbers to a name) and the length.

Validation for empty


Empty validation can be performed using Jquery as follows;
//validation for empty if (name.val() == "") { name.addClass("error"); // adding css error class to the control nameInfo.text("Names cannot be empty!");//filling up error message nameInfo.addClass("error");//add error class to info span return false; } else { name.removeClass("error"); nameInfo.text("*"); nameInfo.removeClass("error"); }

The code above demonstrates the use of variables declared above. The Jquery function val() read the input control value prpperty. First condition is to check for empty values. If the input control value is empty then display the error status to the user. Error status can be implement using CSS classes and Jquery. addClass() and text() functions of JQuery provide grate control, using addClass() we can add a CSS class into any HTML tag. Here we add error class to both nameInfor span and name input box. Now the input box and error text are highlighted. Using text() function we write a specific text into HTML control, in this case we write it for span. Finally the function returns false and no submission will happen. Error status will be shown as below.

validation for empty strings

If the value is not empty then change both controls into normal status. We can achieve this using removeClass() and text() functions. removeClass() function can be used to remove any CSS classes from an html control. Here we use it to remove error CSS class and text() function. It will insert the normal text status to message span.

Validation for length


Length validation is needed to perform for all the text. For example names cannot have only one letter it should be more than two. The code shown below demonstrates how to perform length validation.
//if it's NOT valid if (name.val().length < 2) { name.addClass("error"); nameInfo.text("Names with more than 2 letters!"); nameInfo.addClass("error"); return false; } //if it's valid else { name.removeClass("error"); nameInfo.text("*"); nameInfo.removeClass("error"); //return true; }

Here, the code logic is similar to what we use for empty validation. But only difference is the use of length property. JQuery val() function will read the string value of the html control and JQuery length property. You can decide the text length. Condition will test out for required length and the error logic shown will be the same.

Validation for Lenght

Validation for character only


Character validation will be a bit tricky. The code mentioned below will demonstrate how to perform it.
// validation only for characters no numbers var filter = /^[a-zA-Z]*$/; if (filter.test(name.val())) { name.removeClass("error"); nameInfo.text("*"); nameInfo.removeClass("error"); return true;

} else { name.addClass("error"); nameInfo.text("Names cannot have numbers!"); nameInfo.addClass("error"); return false; }

Now, an extra parameter called filter is used to store the regular expressions. To filter strings for certain patterns, regular expressions are very useful. E.g. Matching telephone number patterns, email address, date patterns etc. Now we have got the regular expression in a variable. So it is time to make use of the text() function as javascript matches the string. The test() method checks for a match in a string. This function returns a Boolean. For a matching string it provides true, where we can clear an error status. The code will show an error if a mismatch takes place as shown below image.

Validation for numbers

Lets check everything together. HTML code will be as follows;


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Untitled Page</title> <link href="style.css" rel="Stylesheet" media="all" /> <!--step one--> <script type="text/javascript" src="js/jquery-1.3.2.min.js"></script> <!--step four--> <script type="text/javascript" src="js/single.js"></script> </head> <body> <!--step two--> <form id="form1" action="" method="post"> <!--step three-->

<div> First Name <input id="txtname" type="text" /> <span id="infotext">*</span><br /> <input id="Submit1" type="submit" value="submit" /> </div> </form> </body> </html>

Javascript code will be as follows;


// JScript source code $(document).ready(function() { //global variables var form = $("#form1"); var name = $("#txtname"); //textbox u are going to validate var nameInfo = $("#infotext"); //to display error message //first validation on form submit form.submit(function() { // validation begin before submit if (validateName()) { return true; } else { return false; } }); //declare name validation function function validateName() { //validation for empty if (name.val() == "") { name.addClass("error"); nameInfo.text("Names cannot be empty!"); nameInfo.addClass("error"); return false; } else { name.removeClass("error"); nameInfo.text("*"); nameInfo.removeClass("error"); } //if it's NOT valid if (name.val().length < 2) { name.addClass("error"); nameInfo.text("Names with more than 2 letters!"); nameInfo.addClass("error"); return false; } //if it's valid else { name.removeClass("error"); nameInfo.text("*"); nameInfo.removeClass("error"); } // validation only for characters no numbers

var filter = /^[a-zA-Z]*$/; if (filter.test(name.val())) { name.removeClass("error"); nameInfo.text("*"); nameInfo.removeClass("error"); return true; } else { name.addClass("error"); nameInfo.text("Names cannot have numbers!"); nameInfo.addClass("error"); return false; } } });

Take a look at the live demo here.

You might also like