Tag Archives: client validation

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

Advertisements

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>