Introduction

In this article, we are going to look at using Jquery, how perform client side validation for input text on HTML forms. Client side validation is highly regarded when it comes to form input data validations. HTML forms collect user inputs, ultimately saved in Databases. This process will need to filter the garbage pumping into databases. Data validation can be divided into two, which are client side validation and server side validation. There are many ready made plug-ins available for free. Let’s consider a very basic example of validating input “Name” client side as shown below html code.

Basic html code

<form id="form1" action="" method="post" >
 <!--step three-->
 <div>
 <span>First Name</span>
 <input id="txtname" type="text" /> <span id="infotext">*</span><br />
 <input id="Submit1" type="submit" value="submit" />
 </div>
</form>

Above piece of code will create a simple html form, a text box, label and a submit button. Let’s dig into details why you need above code. First, you need to place all the input controls  inside the html form. Html form is responsible and executes the action when it is submitted, it can be a GET or POST based on the method setting. The div tag surround by the html input controls is acting as the placeholder to the HTML controls. Without that placeholder DIV you will encounter w3c validation errors. Input text box and infortext span are there to collect the information and display Error messages to users. Finally submit button will trigger the form action when it is being clicked by the user. This will render as follows (PIC1 the basic view)

jquery input validation

How to set the Jquery Reference

Now the form is ready to take off for client side validation. Since we are going to use JQuery for client side validation, we need to refer the JQuery library(You can download Jquery plug-in for free www.jquery.org) . Once you download you can set the reference as follows;

<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>

As a best practice in html coding, you place all your .JS files in a separate folder. Create another JS file call valitioninput.js and save it in the same folder. In this file we will write all our custom validation code. Set the reference to custom js file too.

<script type="text/javascript" src="js/validationinput.js"></script>

Building the JQuery client side validation code

Before you begin any JQuery coding you need to add page ready() event. This is how you place page ready event.

$(document).ready(function() {
//All your code will wirte inside here.
});

The code snippet for events and other will be inside the above method and execute after loading the page in the browser. Like other programming languages in Javascript coding we need to declare variable to read and store input values.

Read Required Inputs from the form

In order to read values from HTML Form controls we need to identify the selectors we are going to use. By using a selector you can read, assign or trigger events of a html controls. You can use three types of selectors to read html controls. They are css class, control ID and the control TAG name. In this scenario I will use pseudo ID to select each element. Now we need to decide what required values are. Here we are going to validate only one text box so the text box value and we use the span tag to display error message. These two will be needed. You can read by selecting them using JQuery as follows;

var name = $("#txtname"); //textbox you are going to validate
var nameInfo = $("#infotext"); //to display error message

As you can see these two lines will be your first lines of code inside the Document Ready Event. These two variables will act global for all other functions within the ready event.

What Events need to validate data client side?

We need to think carefully what events are needed to handle in order to validate this name text box client side. It is obvious that we need to handle the submit event of the Form. Why? Before it is submitted we are supposed to perform client side validation for input controls. When you consider real time environment sometimes users can use the TAB or arrow keys for navigation through text input fields. Assume user fills a form and TAB or used arrow key on a required field the system should validate the input then and there. Having said, we need to handle the input control onBlur event. Let’s consider if the user select mouse instead of the tab or arrow keys then we need to handle onKeyDown event.

Submit event

The below mentioned code shows how to handle form submit button action.

$(“#form1”).submit(function() {
// validation begin before submit
});

Here I’m using 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 triggered when the user click on submit button. Once it is triggered, client side validations for input text box should perform. Since we may need to perform same client side validation in the other two events as well, the best solution will be to create separate function to perform client side validation for text box. By using this approach we can generalize the validation of text box into one central location, which lead to easy maintenance of code. Your submit event handler code will look like 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 or else display client side error messages.

Blur event client side validation call

Same validate function can be called inside the blur event handler. You can add the code below to create blur event validate;

name.blur(validateName);

KeyUp Event client side validation call

As shown above add the code below to handle keyup;

name.keyup(validateName);

Building client side validation function

Inside the event handler you need to identify what validations need to be checked. 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.

Client side validation for empty

Empty client side 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");
 //return true;
 }

The code above demonstrates the use of variables declared above. The Jquery function val() read the input control value property. First condition check for empty values, if the input control value is empty then it displays the error status to the user. Error status can be implemented 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 to span. Finally function returns false and no submission will happen. Error status shown like in the image below.

jquery validation empty
jquery validation empty

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 a html control. Here we use it to remove error CSS class and text() function will insert the normal text status to message span.

Validation for length

For all the text fields you need to perform length validation. For example names cannot have only one letter it should be more than two. The code 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 determine the text length. Condition will check for required length. Display error logic will be the same.

jquery validation-length
jquery validation-length

Validation for character only

Character validation will be bit tricky. Below code will demonstrate how you can 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;
 }

Here we are using an extra parameter called filter to store the regular expression. Regular expressions are very useful for filtering strings for certain patterns. For example you can match telephone number patterns, email address, date patterns etc. Now we have the regular expression in a variable. Now it is  the time to use the text() function if javascript to match the string. The test() method tests for a match in a string. This function returns a Boolean. For a matching string it gives true, where we can clear error status. If a mismatch occurs, code will display error.

jquery validation-lnumber
jquery validation-lnumber

Let’s check putting all together. HTML code will be as follows;

<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;
 }

 }
});

You can look at the live demo here.