Share the ideas and thoughts, become united ...
Showing posts with label form validation. Show all posts
Showing posts with label form validation. Show all posts

Thursday, April 8, 2010

Rapid jQuery: HTML Form Validation

I have showed the idea of basic form validation with jQuery on my previous post. Now I am gonna show you guys how to speed up the validation process by using plug-in. Be ready to be amazed !

What we need :
  1. jQuery 
  2. jQuery Form Validation plug-in
  3. HTML codes :)
First we need to add the jQuery and the plug-in to our webpage which we want to validate.
<script type="text/javascript" src="jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="jquery.validate.min.js"></script>
Now lets have a look at the form which has to be validated.

<form action="submit.php" method="post" id="doit" >
<fieldset>
    <label for="name">Name</label><br />
    <input type="text" id="name" name="name" class="required" minlength="2" /><br />
    <label for="email">Email</label><br />
    <input type="text" name="email" id="email" class="required email" /><br />
    <label for="zip_code">Zip code</label><br />
    <input type="text" name="digits" id="zip_code" class="required digits" /><br />
    <input class="submit" type="submit" value="Submit" />
</fieldset>
</form>
We have to set up some meta data in order to use the built in validation methods. We are using the label to notify the user about the field and also to display the error message. The important part is the for property. It is the same as the id of the component it is representing.
The next important part is the name property it must be one of the predefined class. some of the predefined classes are:
  • name - validation for common name
  • email - validation for email addresses
  • url - validation for url addresses
  • digits - validation for only digits
There are many predefined class. You can check the plug-in's documentation for complete list.
Next important property is class property. You can define your field to be required in the class property.
Note that the email input type has a class value of "required email". It means that the field is a necessary one and it must contain a valid email address.

Hope you have understand the basic behind the validation plug-in. Now we are only one step away from the validation process. Lets check it out -

<script type="text/javascript">
    $(document).ready(function () {
        $("#doit").validate();
    });
</script>
 Now we have to call the validate() method of the form. so we use the $("#doit") to select the whole form. And then call the validate() method to validate it.
Yes the validation is completed. Don't believe me? Why don't you just try it out.

Lastly you can add customization in the CSS section to change the way the message appears.
<style>
    label.error {
        color:#FF0000
    }
</style>
Here is a snapshot of the validation process :


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

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.

Saturday, April 3, 2010

Code n Learn: Form Validation Javascript

We all know that it is the programmer's duty to validate the form against invalid inputs. This checking or validation can be down in two ways. One is Client side, other is Server side.

We will have a quick review on how to validate form in client side using javascript.

Let us consider we have a form with first name, last name, email address and comment.

<form action="submit.php" method="post">
    First name: <input type="text" id="fname" value="" name="fname" /><br />
    Second name:<input type="text" id="lname" value="" name="lname" /><br />
    Email: <input type="text" id="email" value="" name="email" /><br />
    Comment: <input type="text" id="com" value="" name="com" /><br />
     <input type="submit" value="Submit" name="submit" onclick="return validate()" />
</form>
Ok, you may wonder why we add the id to all of the input type? Ids must be unique and we can search a component by its Id. So, we need to have an Id for each field which we will validate.
On the submit button we added onclick="return validate()". Here validate() is the form validation function. Then why we use return in front of it? Its because if the function return false then the form wont be submitted, It will be submitted once it receives true from validate function.

Now we add some basic style using CSS (Cascading Style Sheets). We only need two classes. One when there is a validation failed, other one is when validation is successful.

.error {
    background-color:rgb(255,0,0); /* red color */
}

.valid {
    background-color:rgb(0,255,0);  /* green color */
}
 We assign the error class when validation fails, thus making the component go red indicating an error was detected. You can run you imagination wild when customizing the class. We assign the other when validation success.

Now we only require the validation function to validate the form.
We need to get the handler of the First name & Last name text box. This can be done by searching the element by document.getElementById() function. Then we check the value entered by the user using the value property of that component.
function validate_component(name) {
     var comp = document.getElementById(name);
     if (comp.value == null || comp.value == '' ) {
         comp.className = 'error';      /* assign the css class to this component to indicate validation failure */
         return false;
     } else {
         fname.className = 'valid';    /* valid */
         return true;
     }
}
 We have setup the basic validation method. With this method we can validate first name, last name and comment component. We need to consider the email validation case. Cases to be considered when validating an email are -
  1. Email must have one '@' [at] and at least one '.' [dot]  ( xyz@yyy.ccc )
  2. '@' [at] cannot appear as first element  ( @xyzyyy.ccc )
  3. '.' [dot] cannot appear as last element  ( xyz@yyyccc. )
  4. Last '.' [dot] must be after '@' [at] but not immediate after ( x.y.z@yyy.ccc | x.y.z@.yyyccc )
  5. There can be exactly one '@' [at]
 Now the validation

function validate_email() {
    var error_occured = false;
    var e = document.getElementById('email');
    var email = e.value;
    error_occured = !validate_component('email');   /* check for basic validation */
    var at_index = email.indexOf('@');      /* returns the index of @  or -1 indication there was none */
    var at_last_index = email.lastIndexOf('@');
    var dot_index = email.lastIndexOf('.');
    if ( at_index == 0 || at_index == -1 || at_index != at_last_index || dot_index <= at_index || dot_index - at_index == 1 || dot_index == -1 || email.length - dot_index == 1 ) {
         error_occured = true;
         e.className = 'error';
    } else {
         e.className = 'valid';
    }
    return !error_occured; 
}
 What does what :
  1. at_index == 0 [ '@' was the first element so invalid ]
  2. at_index == -1 [ '@' was not found ! ]
  3. at_index != at_last_index [ There were more than one '@' (invalid) because first @ and last @ have different index number ]
  4. dot_index <= at_index [ '.' was infornt of '@' (invalid) ]
  5. dot_index - at_index == 1 [ '.' was immediately after '@' (invalid) ]
  6. dot_index == -1 [ '.' not found ! ]
  7. email.length - dot_index == 1 [ '.' is the last element (invalid) ]

Now we are ready to integrate all of this to one function.

function validate() {
            /* evaluate values */
    var ev_f_name = validate_component('fname');
    var ev_l_name = validate_component('lname');
    var ev_com = validate_component('com');
    var ev_email = validate_email();
    if ( ev_f_name && ev_l_name && ev_com && ev_email ) {
           return true;
    } else {
           alert('Please fill the form completely and correctly');
           return false;
    }
}
Here you go. The validation is complete. Hope you find it useful. If any suggestion or question please leave a comment.