Example to implement Jquery form validations in asp.net C#,Vb.net

IntroductionIn previous articles i explained JavaScript validation in asp.net website and  How to show Validation guidelines in web forms using JavaScript in Asp.net and Drag & drop to upload multiple files using AjaxFileUpload like Facebook and How to upload file and create Zip file in asp.net using C#,VB.Net and Bind and Export GridView data to PDF file in asp.net and Get Title,Description and Keywords Meta tags from URL in asp.net.
 In this article I am going to implement validations using Jquery. We can also implement validations through validation controls provided by asp.net .You can read my articles on validation controls in asp.net.but in this example I have used Jquery.

implementing Jquery validation  example in asp.net
Click on image to enlarge
 I have created a web form having all the basic fields and implemented the necessary and recommended validations on each field as describes below:
  • Validation implemented on each field is explained as:
Name: can’t be left blank.

User Name: can’t be left blank and should be at least 5 characters long.

Email Id: can’t be left blank and should be in valid email format.

Password: can’t be left blank and should be between 6 - 10 characters.

Confirm Password: can’t be left blank and should be between 6 - 10 characters and must 
match with the Password field.

Website: can’t be left blank and should be in valid URL format e.g. http://www.webcodeexpert.com

Age: can’t be left blank and should be digits and between 20 - 25.

DOB: can’t be left blank and should be valid date format (mm/dd/yyyy)

Mobile No.: can’t be left blank and should be digits and 10 digits long.

Address: can’t be left blank.

Zip Code: can’t be left blank and should be digits and at least 6 digits long.

Hobbies: at least one hobby should be checked

In the <Head> tag of the design page (.aspx) add the following 

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js" type="text/javascript"></script>
        <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.9/jquery.validate.min.js" type="text/javascript"></script>

        <script type="text/javascript">
            $.validator.addMethod("requireOne",
                        function (value, element) {
                            return $('input[type="checkbox"]:checked').size() > 0;
                        },
                        "Missing required status - Must choose one");

            $.validator.setDefaults({ ignore: [] });

            $.validator.setDefaults({
                debug: true,
                success: "data valid"
            });

            $(document).ready(function () {
                $("#form1").validate({
                    focusInvalid: false,
                    focusCleanup: true,
                    debug: false,
                    onkeyup: false,
                    onclick: true,
                    onsubmit: true,
                    onkeyup: false,
                    rules: {
                        <%=txtName.UniqueID %>: {
                            required: true
                        },

                        <%=txtUserName.UniqueID %>: {
                            required: true,
                            minlength: 5
                        },

                        <%=txtEmail.UniqueID %>: {
                            required: true,
                            email: true
                        },

                        <%=txtPwd.UniqueID %>: {
                            required: true,
                            minlength: 6,
                            rangelength: [6, 10]
                        },

                        <%=txtConfirmPwd.UniqueID %>: {
                            required: true,
                            minlength: 6,
                            rangelength: [6, 10],
                            equalTo: "#<%=txtPwd.UniqueID %>"
                        },

                        <%=txtWebsite.UniqueID %>: {
                            required: true,
                            url: true
                        },

                        <%=txtAge.UniqueID %>: {
                            required: true,
                            digits: true,
                            range: [20, 25]
                        },

                        <%=txtDob.UniqueID %>: {
                            required: true,
                            rangelength: [10, 10],
                            date: true
                        },

                        <%=txtMobile.UniqueID %>: {
                            required: true,
                            digits: true,
                            minlength: 10,
                            maxlength: 10
                        },

                        <%=txtAddress.UniqueID %>: {
                            required: true
                        },

                        <%=txtZipCode.UniqueID %>: {
                            required: true,
                            digits: true,
                            minlength: 6
                        },

                        hiddenOptionValidator: {
                            requireOne: true
                        },
                        submitHandler: function(form) {
                            form.submit();
                        }

                    },
                    messages: {
                        <%=txtName.UniqueID %>: {
                            required: "Please enter name"
                        },

                        <%=txtUserName.UniqueID %>: {
                            required: "Please enter username",
                            minlength: "Your user name is too short. Must be at least {0} characters."
                        },

                        <%=txtEmail.UniqueID %>: {
                            required: "Please enter email address"
                        },

                        <%=txtPwd.UniqueID %>: {
                            required: "Please enter password",
                            minlength: "A minimum of {0} digits are required.",
                            rangelength: "Password should be between {0} and {1} characters long"
                        },

                        <%=txtConfirmPwd.UniqueID %>: {
                            required: "Please re-enter password to confirm",
                            minlength: "A minimum of {0} digits are required.",
                            rangelength: "Password should be between {0} and {1} characters long"
                        },
                        <%=txtWebsite.UniqueID %>: {
                            required: "Please enter valid website URL"
                        },
                        <%=txtAge.UniqueID %>: {
                            required: "Please enter age",
                            digits: "Only digits accepted",
                            range: "Age should be between {0} and {1}"
                        },

                        <%=txtDob.UniqueID %>: {
                            required: "Please enter date of birth",
                            rangelength: "Enter valid date format(mm/dd/yyyy)"
                        },

                        <%=txtMobile.UniqueID %>: {
                            required: "Please enter mobile no",
                            digits: "Only digits accepted",
                            minlength: "A minimum of {0} digits are required.",
                            maxlength: "A maximum of {0} digits are required."
                        },

                        hiddenOptionValidator: {
                            requireOne: "Please tick at least one hobby"
                        },

                        <%=txtAddress.UniqueID %>: {
                            required: "Please enter address"
                        },

                        <%=txtZipCode.UniqueID %>: {
                            required: "Please enter zipcode",
                            digits: "Only digits accepted",
                            minlength: "A minimum of {0} digits are required."
                        }
                    }
                });

                $("input[type='checkbox']").click(function () {
                    $("#hiddenOptionValidator").valid();
                });
            });
        </script>

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


<noscript>  <h3 style="color: #FF3300;">
Javascript is not currently enabled in your browser.<br /> You must <a href="http://support.google.com/bin/answer.py?hl=en&answer=23852" target="_blank" >enable Javascript </a> to run this web page correctly.
</h3></noscript>

  • In the <BODY> tag design the form as:
<fieldset style="width:600px;" >
            <legend>Jquery Validation example in asp.net</legend>

            <table>
                <tr>
                    <td><asp:Label ID="lblName" CssClass="lblsize" Text="Name" runat="server"></asp:Label></td>
                    <td><asp:TextBox ID="txtName" runat="server"></asp:TextBox></td>
                </tr>
                <tr>
                    <td> <asp:Label ID="lblUserName" CssClass="lblsize" Text="User Name:" runat="server"></asp:Label>  </td>
                    <td> <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox></td>
                </tr>
                <tr>
                    <td><asp:Label ID="lblEmail" CssClass="lblsize" Text="Email Id:" runat="server"></asp:Label></td>
                    <td><asp:TextBox ID="txtEmail" runat="server"></asp:TextBox></td>
                </tr>
                <tr>
                    <td><asp:Label ID="lblPwd"  CssClass="lblsize" Text="Password:" runat="server"></asp:Label></td>
                    <td><asp:TextBox ID="txtPwd" runat="server"></asp:TextBox></td>
                </tr>
                <tr>
                    <td><asp:Label ID="lblCompPwd" CssClass="lblsize" Text="Confirm Password:" runat="server"></asp:Label></td>
                    <td><asp:TextBox ID="txtConfirmPwd" runat="server"></asp:TextBox></td>
                </tr>
                <tr>
                    <td><asp:Label ID="lblWebsite" CssClass="lblsize" Text="Website:" runat="server"></asp:Label> </td>
                    <td><asp:TextBox ID="txtWebsite" runat="server"></asp:TextBox></td>
                </tr>
                <tr>
                    <td><asp:Label ID="lblAge" CssClass="lblsize" Text="Age:" runat="server"></asp:Label></td>
                    <td><asp:TextBox ID="txtAge" runat="server"></asp:TextBox></td>
                </tr>
                <tr>
                    <td><asp:Label ID="lblDOB" CssClass="lblsize" Text="DOB:" runat="server"></asp:Label></td>
                    <td><asp:TextBox ID="txtDob" runat="server"></asp:TextBox></td>
                </tr>
                <tr>
                    <td><asp:Label ID="lblMobile" CssClass="lblsize" Text="Mobile No.:" runat="server"></asp:Label></td>
                    <td> <asp:TextBox ID="txtMobile" runat="server"></asp:TextBox></td>
                </tr>
                <tr>
                    <td><asp:Label ID="lblAddress" CssClass="lblsize" Text="Address:" runat="server"></asp:Label></td>
                    <td><asp:TextBox ID="txtAddress" runat="server"></asp:TextBox></td>
                </tr>
                <tr>
                    <td><asp:Label ID="lblZip" CssClass="lblsize" Text="Zip code:" runat="server"></asp:Label></td>
                    <td><asp:TextBox ID="txtZipCode" runat="server"></asp:TextBox></td>
                </tr>
                <tr>
                    <td>Hobbies:</td>
                    <td><asp:Label ID="lblCrkt" runat="server" Text="Cricket"></asp:Label>
                    <asp:CheckBox ID="chkCricket" runat="server" />
                    <asp:Label ID="lblFootball" runat="server" Text="Football"></asp:Label>
                    <asp:CheckBox ID="chkFootball" runat="server" /><input id="hiddenOptionValidator" name="hiddenOptionValidator" type="hidden" /></td>
                </tr>              
                <tr>
                    <td>&nbsp;</td>
                    <td>
                        <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click" /> </td>
                </tr>
            </table>
        </fieldset>
  • Create a style sheet to add styles to the form created:
Go to Website menu ->Add New Item ->Select StyleSheet -> Ok.
It will add a StyleSheet.css under your website project in solution explorer. Open the StyleSheet.css and add the following

body {
}

#field{margin-left: .5em;float: right;}

#field, label{float: left;font-family: Arial, Helvetica, sans-serif;font-size: small;}
div{height:17px;}
br{clear: both;}

input{border: 1px solid black;margin-bottom: .5em;}

input.error{border: 1px solid red;}

label.error{position:static;background: url('Images/wrong.png') no-repeat;padding-left: 20px; margin-left: .3em; vertical-align: middle;background-color: #FFEBE8;width: 250px;float:right;}

label.valid{position:inherit;background: url('Images/right.png') no-repeat;display: block; float:right; margin-right:235px; width: 16px;height: 16px;border: none;vertical-align:top;}

.clr{clear:both}
.lblsize{float:left; width:150px;}
.inpsize{float:left; width:200px; margin-right:10px;}
.fldsize{width:640px;}

Also create a folder in the root directory and name it “Images”. Search on Google the images for “tick(right.png in our example)” and “cross(wrong.png in our example)” to show while validation success and failure as in my example

Now over to you: 
"If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned for more technical updates." 
Previous
Next Post »

19 comments

Click here for comments
Anonymous
admin
August 17, 2013 ×

Really nice work ....but the problem is that after validating the form if all entries are correct then button must fire its onclick event, which is not working ......Please help me....
--Deepak

Reply
avatar
PandeyTech
admin
August 19, 2013 ×

great work its working good but the only problem is that.....if all the entries are correct then after validating the form it must perform its onclick event and execute its button click server side code which is not working .....please help me and tell me how to make it work....

Reply
avatar
August 19, 2013 ×

Hello deepak..thanks for notifying the problem..i have re-checked and resolved the error and updated the article..You just need to set debug: false instead of debug: true.

Stay tuned and stay connected for more updates

Reply
avatar
Anonymous
admin
August 19, 2013 ×

thanks...

Reply
avatar
wik hanck
admin
August 22, 2013 ×

This is great thanks!! I appreciate that guys like you make web programming cool for rookies like me.

Reply
avatar
August 22, 2013 ×

thanks wik hanck for appreciation..stay tuned and stay connected for more useful updates..

Reply
avatar
September 10, 2013 ×

Thanks prasanna..keep reading

Reply
avatar
Unknown
admin
September 25, 2013 ×

I Lalit ur arcticles too good regularly i read ur articles pls upload MVC concept.

Reply
avatar
September 25, 2013 ×

Hello Santosh..thanks for your suggestions..i will soon upload some article on MVC..so keep reading for more updates..

Reply
avatar
Anonymous
admin
September 27, 2013 ×

This code is not working for ascx file what should i change in order to apply jquery for it? reply soon

Reply
avatar
Anonymous
admin
September 30, 2013 ×

Can Someone please explain it .I unable to understand .

Reply
avatar
Unknown
admin
October 14, 2013 ×

very good lesson keep going

Reply
avatar
Anonymous
admin
October 14, 2013 ×

we need source code

Reply
avatar
October 14, 2013 ×

Hi, Everything is in this article..read and try this article by copy paste..:)

Reply
avatar
October 14, 2013 ×

Thanks mahammad abuhmian..stay connected and keep reading for more useful updates like this..

Reply
avatar
Unknown
admin
November 30, 2013 ×

Hello Sir...How i can give Validation Group.please help me ..this is excellent code please help me sir...thank you in advance..

Reply
avatar
January 04, 2014 ×

well done , but can please send me the validation for drop down list in jquery as well,
just same code and please add one dropdownlist and validate it

Reply
avatar
Anonymous
admin
May 16, 2015 ×

very good

Reply
avatar

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..