Share the ideas and thoughts, become united ...

Monday, April 5, 2010

Do it with jQuery: HTML Form validation - Source @ Bottom

This is my follow up on my previous post on Form validation with javascript.
This post for those who want to try the form validation with jQuery.

jQuery is a javascript library developed for rapid application development. I,e - One can write less code by using it, so the development of the application is accelerated.

You can learn more about jQuery here.

To get started we need -
  1. HTML page which contains the form.
  2. jQuery Library
  3. Some jQuery codes.

After getting the jQuery libarary we have to add it to our HTML page. Scripts are generally added with in the <head></head> html tags.
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<link type="text/css" href="style.css" rel="stylesheet" />
As you can see that this is done by using a <script> tag. We are gonna use the stylesheet (CSS) to decorate the messages. This will increase the user interactivity.


Now we need the html form which has to be validated.
<body>
<form action="submit.php" method="post">
<table cellpadding="0" cellspacing="0">
<tr><td>
First name: </td><td><input type="text" name="fname" id="fname" /></td><td>
<label id="s_fname"></label>
</td></tr>
</table>
</form>
We need the id field to get the component's handler so that we can manipulate it. Id provides a way to uniquely identify the component.

We now write a little code to register jQuery events with callback functions. All these code goes inside the <head></head> HTML tag.
<script type="text/javascript">
        $(document).ready( function() {
        $("#fname").blur(function () {
jQuery starts now. jQuery uses callback function to handle various event. One of the most import callback is the $(document).ready( function () {} );. When the page loads completely this event is raised. So, in the process of handling we can register more callback function. As we are dealing with the textbox, so we are gonna register the callback function for blur() event. When ever the text box loses focus this event is raised.
So, by registering callback method to it we can check the value of it and decide whether it is valid or not. We uses $(id) to get the component. Then we use the blur(fn) event to register the callback method.

Now we get the value from the textbox and examine it.
            var value = $("#fname").val();
            value = jQuery.trim(value);
            $("#fname").val(value);
First line gets the value of the component by calling the val() method. Then we use a jQuery utility function jQuery.trim(str) to trim the beginning and trailing whitespaces from the input. Then by the third line we again set the new value back to the textbox by using the val(value) method of the component.
            if (value == "" || value == null) {
                $("#s_fname").text("Please enter a name.");
                $("#s_fname").removeClass("valid");
                $("#s_fname").addClass("error");
                $("#fname").removeClass("valid_back");
                $("#fname").addClass("error_back");
            } else {
                $("#s_fname").text("Ok");
                $("#s_fname").addClass("valid");
                $("#s_fname").removeClass("error");
                $("#fname").removeClass("error");
                $("#fname").addClass("valid_back");
            }
        });
      
    });
  
</script>
We check the value for empty or null string. If the value of the textbox is either null or empty ("") then the value is invalid and we notify the user by setting the background of the textbox to red. We also display a red text to notify the user about the error. This is done by using the text(str) method of the component. text(str) sets the text of a component. We use removeClass(class name) and addClass( class name ) to remove and add the visual effect to the textbox defined in the CSS class. Here in the code "valid" and "error" are two CSS class. We use "valid" class to denote that the validation is successful and we use the "error" class to notify user that validation failed.

We now need to code the style.css file. This file contains the CSS class which we have used.

.error {
color:#FF0000;
}

.valid {
color:#006600;
}

.error_back {
background-color:#FF0000;
}

.valid_back {
background-color:#006600;
}
 Every class in the CSS must have a 'dot' (.) before them. In the class definition, we set the color value to red in the error class and we set the color value to greenish in the valid class. These classes are used to show message in red or green color to notify the user. We assign then depending upon the validation of the textbox.

The next to classes are used to change the background-color of the textbox. If the validation succeed then we set it to greenish other wise we set it to red to indicate that validation has failed.

We are all done. This post only shows how to use the jQuery functions for form validation. For a basic form validation you can see the previous post. Here is a snapshot of how it looks -

Update - Here is the source code.
If you have any question or suggestion, please let me know.

4 comments:

  1. ANOTHER SPLENDID BLOG FROM SVN, ITS REALLY OUTSTANDING, THANKS

    ReplyDelete
  2. Cool... will study on it... putting as my bookmark :D :D

    nice work done dosto!!

    ReplyDelete
  3. nice information by the uncultured2.
    but can't understand last 4 lines of the function.
    $("#s_fname").addClass("valid");
    $("#s_fname").removeClass("error");
    $("#fname").removeClass("error");
    $("#fname").addClass("valid_back");
    why is these lines for? i mean, first 5 lines are for printing error message and changing background. but why those last 4 lines for?
    again hats off job.

    ReplyDelete