jQuery UI dialog

A dialog is a floating window that contains a title bar and a content area. The dialog window can be moved, resized and closed with the ‘x’ icon by default.

by jQuery UI

I blogged about showing popup for user confirmation before doing something permanently in our application. This is a rule of thumb when design software. I created a small demo as an example to show how we can show a confirm box before delete record from persistent layer for example database. In that example I used a plain JavaScript confirm box for user confirmation. It may be enough for our simple and in house applications. But for internet based public application we need a more sophisticated solution over a simple JavaScript confirmation box. For that kind of applications we need more beautiful user interface.

We have some options for this problem. We can design a ‘div’ element and design it as an popup and using some JavaScript we can show it when we want the confirmation. But today I am using a library which is from jQuery for my solution. This is jQuery UI plugin. This library has a dependency on jQuery core. That means we need the jQuery core library in our page when we are using this plugin. This plugin has a function called ‘dialog()’ using this function we can popup a simple ‘div’ element as popup. To make things simple I am going to show a simple code.

If we want to show a simple dialog using this plugin then we can use this code.

<!-- CSS for jQuery UI. -->
<link href="../../Content/jquery-ui.min.css" rel="stylesheet" type="text/css" />

<!-- jQuery core library. -->
<script src="../../Scripts/jquery-1.8.3.js" type="text/javascript"></script>   

<!-- jQuery UI plugin. -->
<script src="../../Scripts/jquery-ui-1.9.2.custom.min.js" type="text/javascript"></script>

<script type="text/javascript">
$(document).ready(function () {
    $("#dialog").dialog(); // Show 'div' as a dialog.
});
</script>

<div id="dialog" title="Demo Dialog">
    This is my dialog box.
</div>

This will show the div as a dialog. The title of the ‘div’ will be the title of the dialog. So simple. If we want to show a ‘OK’ button inside our dialog then we can use this code.

$("#dialog").dialog({
    buttons: {
        OK: function () {
            $(this).dialog("close");
        }
    }
});

Dialog function can accept object literal. Through that we can set many option of our dialog. Also this plugin have some theme to select. You can also create your own theme to use. Depending on your theme the CSS can be downloaded. I am here using the most basic theme. In real applications we should use theme which will match our application look and feel, if not then we should create one. For full documentation please take a look at jQuery UI plugin.

Lets go to my main code. I am going to use this plugin to convert my plain confirm box with a more beautiful dialog box in my demo example. First of all I am creating a ‘div’ element as my dialog.

<div id="dialog" title="Delete Confirmation">
    Are you sure?
</div>

Next in the place where I wrote the code to show a plain JavaScript dialog box, I am going to replace that code to this.

// Show confirmation dialog and pass the 'event' paramer
// to use the object inside the function for which the 
// 'click' event fired, in this case the perticular 'delete' link.
$(".deleteLink").click(function (event) {
    $("#dialog").dialog({
        modal: true,
        buttons: {
            OK: function () {
                $(this).dialog("close");
                window.location = "http://<%: Request.Url.Host %>:<%: Request.Url.Port %>/Customer/Delete/" + 
                    event.target.id; // Get the ID of the record from the 'delete' link id.
            },
            Cancel: function () {
                $(this).dialog("close"); // Cancel the 'delete' operation.
            }
        }
    });
});

Also at place where the delete link was I am going to replace that code.

<a class="deleteLink" href="#" id="<%: item.CustomerID %>">Delete</a>

When the user click on the delete link then the dialog will come up for the confirmation. This confirmation have two buttons. One is ‘OK’ and another is ‘Cancel’. Clicking on the ‘Cancel’ button will close the dialog and do nothing. That means it will not continue with the deletion process. But when the ‘OK’ button is clicked the deletion process will continue. For that it will collect some information like host name, port number and the id of the record which will delete (the id of the record is actually the id of the delete link which is dynamically populated using my model object). Using these information dynamically the deletion link is created and call the deletion controller. The deletion controller will actually continue the process at the server side. For simplicity I am not discussing the deletion logic here. Also it is out of my present discussion.

So the full code will be following.

<%@ Page 
    Title="" 
    Language="C#" 
    MasterPageFile="~/Views/Shared/Site.Master" 
    Inherits="System.Web.Mvc.ViewPage<IEnumerable<MvcApplication1.Models.Customer>>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Index
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">  
  
    <link href="../../Content/jquery-ui.min.css" rel="stylesheet" type="text/css" />

    <script src="../../Scripts/jquery-1.8.3.js" type="text/javascript"></script>   
    <script src="../../Scripts/jquery-ui-1.9.2.custom.min.js" type="text/javascript"></script>
    
    <script language="javascript" type="text/javascript">
        $("document").ready(function () {
            
            // Show confirmation dialog and pass the 'event' paramer
            // to use the object inside the function for which the 
            // 'click' event fired, in this case the perticular 'delete' link.
            $(".deleteLink").click(function (event) {
                $("#dialog").dialog({
                    modal: true,
                    buttons: {
                        OK: function () {
                            $(this).dialog("close");
                            window.location = "http://<%: Request.Url.Host %>:<%: Request.Url.Port %>/Customer/Delete/" + 
                                event.target.id; // Get the ID of the record from the 'delete' link id.
                        },
                        Cancel: function () {
                            $(this).dialog("close"); // Cancel the 'delete' operation.
                        }
                    }
                });
            });
        });
    </script>

    <h2>Index</h2>

    <table>
        <tr>
            <th></th>
            <th>CustomerID</th>
            <th>CompanyName</th>
            <th>ContactName</th>
            <th>ContactTitle</th>
            <th>Address</th>
            <th>City</th>
            <th>Region</th>
            <th>PostalCode</th>
            <th>Country</th>
            <th>Phone</th>
            <th>Fax</th>
        </tr>
        <% foreach (var item in Model)
            { %>
        <tr>
            <td>
                <%: Html.ActionLink("Edit", "Edit", new { id = item.CustomerID }) %> |
                <%: Html.ActionLink("Details", "Details", new { id = item.CustomerID })%> |

                <!-- Store the ID of the record for use at the time of deletion. -->
                <a class="deleteLink" href="#" id="<%: item.CustomerID %>">Delete</a>
            </td>
            <td><%: item.CustomerID %></td>
            <td><%: item.CompanyName %></td>
            <td><%: item.ContactName %></td>
            <td><%: item.ContactTitle %></td>
            <td><%: item.Address %></td>
            <td><%: item.City %></td>
            <td><%: item.Region %> </td>
            <td><%: item.PostalCode %></td>
            <td><%: item.Country %></td>
            <td><%: item.Phone %></td>
            <td><%: item.Fax %></td>
        </tr>
        <% } %>
    </table>

    <p><%: Html.ActionLink("Create New", "Create") %></p>

    <div id="dialog" title="Delete Confirmation">
        Are you sure?
    </div>
</asp:Content>
jQuery Dialog
jQuery Dialog

Happy coding.

Confirmation before proceed

There are some basic rule of UI development. One of them is take confirmation from the user before doing something permanently. For example suppose there is a delete option in our UI. When the user click on this option then we should ask for a confirmation from the user that if they really want to delete the record or they click on this option by accidently. It is like giving a second chance to the user.

The most basic option to take confirmation from the user is using the standard confirmation box in browser. We can use it with some JavaScript.

confirm("Are you sure?");

It will show a small modal popup in the browser with a OK and CANCEL button. After showing the confirmation box we can take our decision according the user interaction. In other words we can track the user choice. weather they click on OK button or CANCEL button. For OK it will return true and for CANCEL return false.

var isConfirmed = confirm("Are you sure?");
if (isConfirmed) {
    // Continue with the operation.
}
else {
    // Cancel the operation.
}

As a demo, I am working on a ASP.NET MVC application, on which I am showing all the ‘Customer’ data from ‘Northwind’ database inside one of a view.

//
// GET: /Customer/

public ActionResult Index()
{
    // Get all 'Customer' data using 'ADO.NET Entity Framework'.
    NorthwindEntities entities = new NorthwindEntities();
    IList<Customer> customers = entities.Customers.ToList();

    return View(customers);
}

Now I am creating a view to show all the ‘Customer’ data. I am using html table in my view. Also I am including some links for basic operation like edit, delete etc in the table.

<table>
    <tr>
        <th></th>
        <th>CustomerID</th>
        <th>CompanyName</th>
        <th>ContactName</th>
        <th>ContactTitle</th>
        <th>Address</th>
        <th>City</th>
        <th>Region</th>
        <th>PostalCode</th>
        <th>Country</th>
        <th>Phone</th>
        <th>Fax</th>
    </tr>
    <% foreach (var item in Model)
        { %>
    <tr>
        <td>
            <%: Html.ActionLink("Edit", "Edit", new { id = item.CustomerID }) %> |
            <%: Html.ActionLink("Details", "Details", new { id = item.CustomerID })%> |      
                          
            <!-- 
                Give a css class to the 'delete' link so that we 
                can get the 'delete' link using jQuery easily. 
                'new { @class = "deleteLink" }' this is the syntax 
                to add css class. 
            -->
            <%: Html.ActionLink("Delete", "Delete", new { id = item.CustomerID }, new { @class = "deleteLink" })%> 
        </td>
        <td><%: item.CustomerID %></td>
        <td><%: item.CompanyName %></td>
        <td><%: item.ContactName %></td>
        <td><%: item.ContactTitle %></td>
        <td><%: item.Address %></td>
        <td><%: item.City %></td>
        <td><%: item.Region %> </td>
        <td><%: item.PostalCode %></td>
        <td><%: item.Country %></td>
        <td><%: item.Phone %></td>
        <td><%: item.Fax %></td>
    </tr>
    <% } %>
</table>

When the user click on the delete link then we should show a confirmation popup because this operation will remove the record permanently from the database. For that I am using some JavaScript and jQuery code.

$("document").ready(function () {
    $(".deleteLink").click(function () {                
        // Show the confirm box when delete link is clicked.
        var isConfirmed = confirm("Are you sure?");

        // Check the user decision and take action 
        // according to that.
        if (isConfirmed) {
            return true; // Yes, delete the record.
        }
        else {
            return false; // No, cancel the delete operation.
        }
    });
});

So if user click on the OK button then we can continue with the delete operation otherwise cancel it. In the case of OK button I am returning true that means it will submit to the server to continue with the delete operation and in the case of CANCEL I am returning false that means it will not submit to the server and the delete operation can not be able to continue.

So the full code of the view is:

<%@ Page 
    Title="" 
    Language="C#" 
    MasterPageFile="~/Views/Shared/Site.Master" 
    Inherits="System.Web.Mvc.ViewPage<IEnumerable<MvcApplication1.Models.Customer>>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Index
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">    
    
    <!-- Attach jQuery library. -->
    <script src="../../Scripts/jquery-1.8.3.js" type="text/javascript"></script>        
    
    <script language="javascript" type="text/javascript">
        $("document").ready(function () {
            $(".deleteLink").click(function () {                
                // Show the confirm box when delete link is clicked.
                var isConfirmed = confirm("Are you sure?");

                // Check the user decision and take action 
                // according to that.
                if (isConfirmed) {
                    return true; // Yes, delete the record.
                }
                else {
                    return false; // No, cancel the delete operation.
                }
            });
        });
    </script>

    <h2>Index</h2>

    <table>
        <tr>
            <th></th>
            <th>CustomerID</th>
            <th>CompanyName</th>
            <th>ContactName</th>
            <th>ContactTitle</th>
            <th>Address</th>
            <th>City</th>
            <th>Region</th>
            <th>PostalCode</th>
            <th>Country</th>
            <th>Phone</th>
            <th>Fax</th>
        </tr>
        <% foreach (var item in Model)
            { %>
        <tr>
            <td>
                <%: Html.ActionLink("Edit", "Edit", new { id = item.CustomerID }) %> |
                <%: Html.ActionLink("Details", "Details", new { id = item.CustomerID })%> |      
                          
                <!-- 
                    Give a css class to the 'delete' link so that we 
                    can get the 'delete' link using jQuery easily. 
                    'new { @class = "deleteLink" }' this is the syntax 
                    to add css class.
                -->
                <%: Html.ActionLink("Delete", "Delete", new { id = item.CustomerID }, new { @class = "deleteLink" })%> 
            </td>
            <td><%: item.CustomerID %></td>
            <td><%: item.CompanyName %></td>
            <td><%: item.ContactName %></td>
            <td><%: item.ContactTitle %></td>
            <td><%: item.Address %></td>
            <td><%: item.City %></td>
            <td><%: item.Region %> </td>
            <td><%: item.PostalCode %></td>
            <td><%: item.Country %></td>
            <td><%: item.Phone %></td>
            <td><%: item.Fax %></td>
        </tr>
        <% } %>
    </table>

    <p><%: Html.ActionLink("Create New", "Create") %></p>
</asp:Content>
Confirmation Box
Confirmation Box

Happy coding.

jQuery validation plugin – Sign Up form

I blogged about jQuery validation plugin before. I created a small and very basic example to show how this plugin works. Today I am creating a sign up form demo using this plugin. This will be a html form and I am only doing the use of validation plugin. That means I am not doing any thing server side logic. But in real application we should do server side logic also to register the user in our application. We can use any server side logic for that. This demo example has a basic registration form which has Name, User Name, Password, Email etc. In this example I am going to use two JavaScript libraries. jQuery core and jQuery validation plugin. Also I will create an external JavaScript files for this sign up form. We should use external JavaScript files whenever possible. We should keep apart any programming logic from html markup to make it more maintainable. Also browser download the script first time and cached for future use. It will speed up our web site. For the same reason I will write all my CSS in external files. Ok enough of theory now lets start some coding and develop the demo.

Sign Up Form

So I am creating my registration form. It has name, user name, password, confirm password, email, security question, security answer.

<form id="frmSignUp"> <!-- In real application we should use proper action and method attrebutes. -->                
    <table id="tblSignUp">
        <tr>
            <td>Name</td>
            <td><input type="text" id="txtName" name="txtName" /></td>
        </tr>
        <tr>
            <td>User Name</td>
            <td><input type="text" id="txtUserName" name="txtUserName" /></td>
        </tr>
        <tr>
            <td>Password</td>
            <td><input type="password" id="txtPassword" name="txtPassword" /></td>
        </tr>
        <tr>
            <td>Retype Password</td>
            <td><input type="password" id="txtRetypePassword" name="txtRetypePassword" /></td>
        </tr>
        <tr>
            <td>Email</td>
            <td><input type="text" id="txtEmail" name="txtEmail" /></td>
        </tr>
        <tr>
            <td>Security Question</td>
            <td><input type="text" id="txtSecurityQuestion" name="txtSecurityQuestion" /></td>
        </tr>
        <tr>
            <td>Security Answer</td>
            <td><input type="text" id="txtSecurityAnswer" name="txtSecurityAnswer" /></td>
        </tr>
        <tr>
            <td></td>
            <td>
                <input type="submit" id="btnSubmit" name="btnSubmit" value="Sign Up" />
                <input type="reset" id="btnReset" name="btnReset" value="Cancel" />
            </td>
        </tr>
    </table>
</form>	

Now I am including two JavaScript libraries into my project. jQuery core and jQuery validation plugin. All our validation logic will be in an external JavaScript file.

$(document).ready(function () {
    $('#frmSignUp').validate({
        rules: {
            txtName: {
                required: true,
                maxlength: 20
            },
            txtUserName: {
                required: true,
                maxlength: 20
            },
            txtPassword: {
                required: true,
                minlength: 6,
                maxlength: 10
            },
            txtRetypePassword: {
                equalTo: '#txtPassword'
            },
            txtEmail: {
                required: true,
                email: true
            },
            txtSecurityQuestion: {
                required: true,
                maxlength: 20
            },
            txtSecurityAnswer: {
                required: true,
                maxlength: 20
            }
        },
        messages: {
            txtName: {
                required: 'Please enter name.',
                maxlength: 'Name must have maximum 20 chars.'
            },
            txtUserName: {
                required: 'Please enter user name.',
                maxlength: 'User name must have maximum 20 chars.'
            },
            txtPassword: {
                required: 'Please enter password.',
                minlength: 'Password must have minimum 6 chars.',
                maxlength: 'Password must have maximum 10 chars.'
            },
            txtRetypePassword: {
                equalTo: 'Password and confirm password must be same.'
            },
            txtEmail: {
                required: 'Please enter email.',
                email: 'Please enter valid email.'
            },
            txtSecurityQuestion: {
                required: 'Please enter security question.',
                maxlength: 'Security question must have maximum 20 chars.'
            },
            txtSecurityAnswer: {
                required: 'Please enter security answer.',
                maxlength: 'Security answer must have maximum 20 chars.'
            }
        }
    });
});

Also I am writing some CSS for basic layout of the form. Now I am adding all the external CSS and JavaScript files into our html form.

<link href="Styles/SignUp.css" rel="stylesheet" type="text/css" />

<script src="Scripts/jquery-1.8.3.js" type="text/javascript"></script>
<script src="Scripts/jquery.validate.js" type="text/javascript"></script>
<script src="Scripts/Validation.js" type="text/javascript"></script>
<script src="Scripts/Utility.js" type="text/javascript"></script>

Our code is ready. Now run it to browser and test the validation logic. Take a closer look at the validation messages. If you can able to fill all the fields with valid values then the form will successfully submits.

Full code

html form

<!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>Sign Up</title>

    <link href="Styles/SignUp.css" rel="stylesheet" type="text/css" />

    <script src="Scripts/jquery-1.8.3.js" type="text/javascript"></script>
    <script src="Scripts/jquery.validate.js" type="text/javascript"></script>
    <script src="Scripts/Validation.js" type="text/javascript"></script>
    <script src="Scripts/Utility.js" type="text/javascript"></script>
</head>
<body>
    <div id="dvWraper">
        
        <div id="dvHeader">
            <h1>Sign Up for a New User</h1>
        </div>       
         
        <div id="dvBody">
            <form id="frmSignUp"> <!-- In real application we should use proper action and method attrebutes. -->                
                <table id="tblSignUp">
                    <tr>
                        <td>Name</td>
                        <td><input type="text" id="txtName" name="txtName" /></td>
                    </tr>
                    <tr>
                        <td>User Name</td>
                        <td><input type="text" id="txtUserName" name="txtUserName" /></td>
                    </tr>
                    <tr>
                        <td>Password</td>
                        <td><input type="password" id="txtPassword" name="txtPassword" /></td>
                    </tr>
                    <tr>
                        <td>Retype Password</td>
                        <td><input type="password" id="txtRetypePassword" name="txtRetypePassword" /></td>
                    </tr>
                    <tr>
                        <td>Email</td>
                        <td><input type="text" id="txtEmail" name="txtEmail" /></td>
                    </tr>
                    <tr>
                        <td>Security Question</td>
                        <td><input type="text" id="txtSecurityQuestion" name="txtSecurityQuestion" /></td>
                    </tr>
                    <tr>
                        <td>Security Answer</td>
                        <td><input type="text" id="txtSecurityAnswer" name="txtSecurityAnswer" /></td>
                    </tr>
                    <tr>
                        <td></td>
                        <td>
                            <input type="submit" id="btnSubmit" name="btnSubmit" value="Sign Up" />
                            <input type="reset" id="btnReset" name="btnReset" value="Cancel" />
                        </td>
                    </tr>
                </table>
            </form>
        </div>       
         
        <div id="dvFooter">
            Copyright @ 2012 Sign Up Form
        </div>

    </div>
</body>
</html>

Validation logic

$(document).ready(function () {
    $('#frmSignUp').validate({
        rules: {
            txtName: {
                required: true,
                maxlength: 20
            },
            txtUserName: {
                required: true,
                maxlength: 20
            },
            txtPassword: {
                required: true,
                minlength: 6,
                maxlength: 10
            },
            txtRetypePassword: {
                equalTo: '#txtPassword'
            },
            txtEmail: {
                required: true,
                email: true
            },
            txtSecurityQuestion: {
                required: true,
                maxlength: 20
            },
            txtSecurityAnswer: {
                required: true,
                maxlength: 20
            }
        },
        messages: {
            txtName: {
                required: 'Please enter name.',
                maxlength: 'Name must have maximum 20 chars.'
            },
            txtUserName: {
                required: 'Please enter user name.',
                maxlength: 'User name must have maximum 20 chars.'
            },
            txtPassword: {
                required: 'Please enter password.',
                minlength: 'Password must have minimum 6 chars.',
                maxlength: 'Password must have maximum 10 chars.'
            },
            txtRetypePassword: {
                equalTo: 'Password and confirm password must be same.'
            },
            txtEmail: {
                required: 'Please enter email.',
                email: 'Please enter valid email.'
            },
            txtSecurityQuestion: {
                required: 'Please enter security question.',
                maxlength: 'Security question must have maximum 20 chars.'
            },
            txtSecurityAnswer: {
                required: 'Please enter security answer.',
                maxlength: 'Security answer must have maximum 20 chars.'
            }
        }
    });

    $('#btnReset').click(function () {
        $('#frmSignUp').validate().resetForm(); // Reset all validation errors when clicking on 'Reset' button.
    });
});

CSS for basic layout

/* Main layout
----------------------------------------- */

body 
{
    font-family: Calibri;
    font-size: 14px;
    margin: 0px;
}

#dvWraper
{
    margin-left: 10%;
    margin-right: 10%;
    border-right-style: solid;
    border-left-style: solid;
    border-right-width: thin;
    border-left-width: thin;
    border-right-color: #336699;
    border-left-color: #336699;
}

#dvHeader, #dvBody, #dvFooter
{
    padding: 2px;
}

#dvHeader
{
    background-color: #E9E9E9;
    color: #336699;
    border-bottom-style: solid;
    border-bottom-width: thick;
    border-bottom-color: #336699;
}

#dvBody
{
    height: 350px;
}

#dvFooter
{
    border-top-style: solid;
    border-top-width: thin;
    border-top-color: #336699;
    background-color: #E9E9E9;
    height: 30px;
    color: #8F8F8F;
    font-size: 12px;
}

/* Input form styles.
------------------------------------------*/

#tblSignUp
{
    margin-top: 10px;
    margin-left: 300px;
}

#tblSignUp input[type='text'], #tblSignUp input[type='password']
{
    width: 300px;
    padding: 5px;
    font-family: Calibri;
    font-size: 14px;
}

#tblSignUp input[type='submit'], #tblSignUp input[type='reset']
{
    font-family: Calibri;
    font-size: 14px;
    background-color: #E9E9E9;
    width: 70px;
    height: 30px;
}

#tblSignUp td
{
    padding: 2px;
}

#dvButton
{
    text-align: right;
}

/* Styles for invalid fields.
---------------------------------------*/

input.error
{
    background-color: #FFDDDD;
}

label.error
{
    color: Red;
}
Sign Up
Sign Up

Validation with jQuery validation plugin

I blogged about client validation using jQuery before. That was a basic validation. An imperative solution. To day I am going to use a declarative solution with jQuery validation plugin.

Why we use validation plugin?

Input validation is very common in our daily life software development. So every time when we submit some data from browser to server side there are some requirement to validate the data before processing or store at some external data sources like databases. Now we need to validate our data in two places. At the client end and the server end. Where server end validation is the real validation and client side validation is for performance. The main discussion today is related to client side validation. Client side validation is done using scripting languages like JavaScript. We know about client side validation using JavaScript and even jQuery. But the problem is every time we have to write almost common code to implement validation at the client side. So we need some more easy solution for this common task. jQuery has a validation plugin which is being used for validation. The syntax is easy, short, can be quickly implemented and declarative. That means we just instruct the plugin what we want to do, not how to do. The plugin is intelligent enough to implement the logic for us.

What we need to use the plugin?

jQuery validation plugin is build on jQuery library. So we need the jQuery core library in our project. Also we can use the jQuery library which is hosted online from Microsoft, Google or jQuery. After adding the jQuery core library we need to download the validation plugin from here and attach that in our web page along with core library. Now we are ready to go.

An example with jQuery validation plugin

Now its time to dirty our hands with some real jQuery validation plugin code. First I am going to create a new HTML web page in notepad and put some input text box to show the validation plugin. Also I am putting a submit button in the form. In this case I am not doing any server side validation. But in real application we should do that because client side validation is not reliable, one can easily turn off the JavaScript in browser and put some invalid data to the server.

Now attach the external jQuery core and jQuery plugin validation to our html page. We can validate a form field in two ways. Basic way and the more advance way.

Basic solution

In the basic way we have to put CSS class name to the form fields. For example I am putting a CSS class in the user name field with the name required. Now inside the jQuery ready function I am writing the code to validate the user name field. For that first I am taking the form and use the validate function of the jQuery plugin to validate. So our code will be like that.

$(document).ready(function () {
    $('form').validate();        
});
<input type="text" id="userName" name="userName" class="required" />

Now if you want to give a error message at the time when user name will be blank then you can add a title attribute in the textbox.

<input type="text" id="userName" name="userName" class="required" 
    title="Please enter user name." />

Now if you want to add another validation to the field then you have to add a CSS class name, like that

<input type="text" id="email" name="email" class="required email" 
    title="Please enter user name." />

In this way we can implement the basic validation. But in basic validation there are some limitations when we want more control over our valid logic. For example if we want to give two different error messages for two validation one for required and another for valid email in our email textbox, then we can not do in this basic validation procedure. Another problem is this basic solution is that our validation rules are scattered through out the page markup. So we have to use the more advance validation procedure.

Advance solution

In this procedure we do not write any validation rules in the page markup for example in our textboxes. The validation function of the jQuery validation plugin take parameter as object literal. In this object literal we can implement the validation rules, messages and many more. So our code will be like that

$('#form1').validate({
    rules: {
        email: {
            required: true,
            email: true 
        }
    }
});

In this case we define two rules to our email field. But what about error messages? If we do not set any error message then the default message will be shown for different rules. This default error message is sufficient for normal situation. But if we need to set error message our self then we can do this.

$('#form1').validate({
    rules: {
        email: {
            required: true,
            email: true 
        }
    },
    messages: {
        email: {
            required: "Please enter email.",
            email: "Please enter a valid email." 
        }
    }
});

Now I am going to add another textbox in our form. Also add validation rules and messages for it.

$('#form1').validate({
    rules: {
        email: {
            required: true,
            email: true 
        },
        dob: {
            required: true,
            date: true 
        }
    },
    messages: {
        email: {
            required: "Please enter email.",
            email: "Please enter a valid email." 
        },
        dob: {
            required: "Please enter date of birth.",
            date: "Please enter valid date."
        }
     }
});
<input type="text" id="email" name="email" />
<br />
<input type="text" id="dob" name="dob" />
<br />
<input type="submit" value="Submit" />

In this way we can implement various validation rules by using jQuery validation plugin. The thing which I like most is we do not implement the logic we only tell what rules and messages we want in our validation.

Full code

<html>
<head>
    <title>jQuery Validation Plugin</title>

    <script type="text/javascript" src="jquery-1.8.3.js"></script>
    <script type="text/javascript" src="jquery.validate.js"></script>

    <script type="text/javascript">
        $(document).ready(function() {
	    $('#form1').validate({
                rules: {
                    email: {
                        required: true,
                        email: true 
                    },
                    dob: {
                        required: true,
                        date: true 
                    }
                },
                messages: {
                    email: {
                        required: "Please enter email.",
                        email: "Please enter a valid email." 
                    },
                    dob: {
                        required: "Please enter date of birth.",
                        date: "Please enter valid date."
                    }
                }
            });
        });
    </script>
</head>
<body>
    <form id="form1">
        <input type="text" id="email" name="email" />
        <br />
        <input type="text" id="dob" name="dob" />
        <br />
        <input type="submit" value="Submit" />
    </form>
</body>
</html>

jQuery effects and animations

As we all know jQuery is a java script library. It has many advantages. For example, write less and do more, cross browser support, we can do various java script effects and animations, AJAX enabled, HTML DOM manipulating is very easy, easy syntax which is easy to write code, it is free and open source etc. That is way jQuery is very popular java script library. Many are using this library in their projects for various types of work. There are also some plugin which is built on top of jQuery library. For example jQuery validation plugin, jQuery UI etc. Also jQuery team has introduced a version for mobile platform. I hope it will also become very popular like his desktop counterpart.

So actually in web application we need to do various types of effect and animation using client end scripting. Now it is very common to use jQuery for this kind of work. It uses java script under the hood. jQuery has some function for effects and animations. For example hide(), show(). For more details about these functions you can search the web or go to jQuery site.

Now today I have created a short demo ASP.NET application and do some effect and animation work with HTML documents. For that I have used jQuery.

Now let’s start from the beginning of my demo application. I have created a new ASP.NET Web Application in Visual Web Developer (VWD) 2010 Express Edition. Now by default VWD add jQuery library in the project template. You can find it in ‘Scripts’ folder in your solution. It is jQuery 1.4.1. Here you can find three files of jQuery. ‘jquery-1.4.1.js’ is for jQuery library. ’jquery-1.4.1.min.js’ is for minified library and ‘jquery-1.4.1-vsdoc.js’ is created by Microsoft which is used by VWD. Minified library is for production server. It is light and all the variables has single letter name and all comments and spaces are removed. So it is not suitable for human reading. For debugging and reading purpose normal jQuery library is suitable. Also the minified counterpart is also less in size that means less time it will take to download in the client computer. Now in Default.aspx I have written some html at the second content area.

<div id="divWraper">
    <div id="divButtons">
        <input type="button" id="btnAnimate" name="btnAnimate" value="Hide" />
        <input type="button" id="btnLightTheme" name="btnLightTheme" value="Light Theme" />
        <input type="button" id="btnDarkTheme" name="btnDarkTheme" value="Dark Theme" />
    </div>
    <div id="divSampleText">
        This is example text. This is example text. This is example text. This is example
        text. This is example text. This is example text. This is example text. This is
        example text. This is example text. This is example text.This is example text. This
        is example text. This is example text. This is example text. This is example text.
        This is example text. This is example text. This is example text. This is example
        text. This is example text.This is example text. This is example text. This is example
        text. This is example text. This is example text. This is example text. This is
        example text. This is example text. This is example text. This is example text.This
        is example text. This is example text. This is example text. This is example text.
        This is example text. This is example text. This is example text. This is example
        text. This is example text. This is example text.
    </div>
</div>

Now I have written some CSS at the first content area to give some style for the html.

#animateButton, #lightThemeButton, #darkThemeButton
{
    background-color: ButtonFace;
    color: ButtonText;
}
        
#divSampleText
{
    width: 97%;
    text-align: justify;
    padding: 10px;
}
        
.Light
{
    color: Black;
    background-color: Silver;
    border: thin solid black;
}
        
.Dark
{
    color: Silver;
    background-color: Black;
    border: thin solid yellow;
}

You can see here that there are two CSS classes, Light and Dark. This classes having some colour theme for light and dark respectively. The plan is that when user will click on the ‘light theme’ and ‘dark theme’ button then the respective colour theme will be applied to the underling demo text area.

Also there is a show/hide button. When user will click on that button then the demo text area will animate. The type of the animation in this case is, it will slide out and slide in. Also depending on the status of the demo text area the show/hide button face will change. So let’s take a look at the jQuery code.

<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
    // My code goes here...
</script>
$(document).ready(function () {

    // It will set light theme at the start.
    $("#divSampleText").addClass("Light");

    // Dynamically change light and dark theme. It is necessary to remove 
    // the dark class before set to light and vice varsa.
    $("#btnLightTheme").click(function () {
        $("#divSampleText").removeClass("Dark");
        $("#divSampleText").addClass("Light");
    });
    $("#btnDarkTheme").click(function () {
        $("#divSampleText").removeClass("Light");
        $("#divSampleText").addClass("Dark");
    });

    // Toggle show and hide the demo text area and change the button face.
    // To change the button face I have used call back function.
    $("#btnAnimate").click(function () {
        $("#divSampleText").slideToggle(function () {
            if ($("#divSampleText").is(":hidden")) {
                $("#btnAnimate").val("Show");
            }
            else {
                $("#btnAnimate").val("Hide");
            }
        });
    });
});

First it will check the html document loading is complete or not. Then it will start his job. First it will set light theme to the demo text. It is for start-up theme. Then it will change theme depending on the user action. For that I have used jQuery addClass() and removeClass() functions. It will add and remove the CSS class. After that when user click the show/hide button then the animation take place and button face will change. To change the button face I have used call back function. That means I have passed a function definition to the slideToggle() function parameter. When the slideToggle() function will finished his animation then it will call the call back function and button face will change. Without using call back function I cannot do it. If I wrote it in the next line then it will execute even before the animation is going. But I need the button face change only after the completion of the animation. So call back function is the solution.

Now my full demo is ready. Running it and click on the buttons and check the results. Can you see how much it is easy using jQuery? I will encourage you to go to jQuery documentation for more information on the functions. Also there are many more to know about jQuery effects and animations.