Article

JQuery Validation In Asp.net Web Form

06 Feb 2018 Kamal Pratap
0 Comments 764 Views



JQuery validation is a standard method to validate form data entries using jQuery Validation Plugin in web pages at client side.

 

The main advantages of JQuery validation is that it validates all field data at client side and reduce the server process.

Asp.net consists various form fields like TextBox, DropDownList, ListBox, CheckBox, RadioButton etc. We use JQuery to validate the field’s data in the form of Required, Email, Password confirmation, Minimum and Maximum Length, Phone Number, Mobile Number, Date Format, Credit Card Number.

JQuery Plugin : Click download button to download the jquery plugin and upload it in your project root directory. 

    <script src="js/jquery.min.js" type="text/javascript"></script>
    <script src="js/jquery.validate.js" type="text/javascript"></script>
    <script type="text/javascript">
            $.validator.addMethod("requireOneHobbie",
                        function (value, element) {
                            return $('input[type="checkbox"]:checked').size() > 0;
                        },
                        "Please tick at least one hobby");

             $.validator.addMethod("requireOneMarital",
                        function (value, element) {
                            return $('input[type="radio"]:checked').size() > 0;
                        },
                        "Please tick at marital status");

             $.validator.addMethod("validDOB",
                function(value, element) {              
                  
                    //var from = value.split(" "); // DD MM YYYY
                    var from = value.split("-"); // DD/MM/YYYY

                    var day = from[0];
                    var month = "JanFebMarAprMayJunJulAugSepOctNovDec".indexOf(from[1]) / 3 + 1;
                    var year = from[2];
                    var age = 18;

                    var mydate = new Date();
                    mydate.setFullYear(year, month-1, day);

                    var currdate = new Date();
                    var setDate = new Date();

                    setDate.setFullYear(mydate.getFullYear() + age, month-1, day);

                    if ((currdate - setDate) > 0){
                        return true;
                    }else{
                        return false;
                    }
                },
                "Sorry, you must be 18 years of age to apply"
            );

            $.validator.addMethod('notzero', 
                function(value, element) {        
                  if(value.charAt(0)== 0)
                    {           
                        return false;
                    }
                  else
                    {
                     return true;
                    }
                },'Mobile number can be start with 0');
                         
            $.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: 6
                        },
                        <%=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: [11, 11],
                            date: true,
                            validDOB : true
                        },
                        <%=txtMobile.UniqueID %>: {
                            required: true,
                            digits: true,
                            minlength: 10,
                            maxlength: 10,
                            notzero:true
                        },
                        <%=txtAddress.UniqueID %>: {
                            required: true
                        },
                        <%=txtZipCode.UniqueID %>: {
                            required: true,
                            digits: true,
                            minlength: 6
                        },
                        hiddenOptionValidatorchkHobbied: {
                            requireOneHobbie: true
                        },                        
                        hiddenOptionValidatorrbtnMarried: {
                            requireOneMarital: 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",
                            email:"Please enter a valid 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: "Please enter age in numerals only",
                            range: "Age should be between {0} and {1}"
                        },
                        <%=txtDob.UniqueID %>: {
                            required: "Please enter date of birth",
                            date:"Enter a valid date of birth",
                            rangelength: "Enter valid date format(dd-MMM-yyyy)"
                        },
                        <%=txtMobile.UniqueID %>: {
                            required: "Please enter mobile number",
                            digits: "Mobile number should be numerals only",
                            minlength: "A minimum of {0} digits are required.",
                            maxlength: "A maximum of {0} digits are required."
                        },
                        <%=txtAddress.UniqueID %>: {
                            required: "Please enter address"
                        },
                        <%=txtZipCode.UniqueID %>: {
                            required: "Please enter zipcode",
                            digits: "Zip code should be numerals only",
                            minlength: "A minimum of {0} digits are required."
                        },                        
                        hiddenOptionValidatorchkHobbied: {
                            requireOneHobbie: "Please tick at least one hobby"
                        },                        
                        hiddenOptionValidatorrbtnMarried: {
                            requireOneMarital: "Please select marital status"
                        }                    
                    }
                });

                $("input[type='checkbox']").click(function () {
                    $("#hiddenOptionValidatorchkHobbied").valid();
                });

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

CSS : Include these CSS style in the head section of the page.

<style>
        #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 doted red;
        }
        
        label.error
        {
            position: static;
            background: url('images/unchecked.gif') no-repeat;
            padding-left: 20px;
            margin-left: .3em;
            vertical-align: middle;
            width: 250px;
            float: right;
        }
        
        label.valid
        {
            position: inherit;
            background: url('images/checked.gif') 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;
        }
    </style>

HTML Markup :

<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:CheckBoxList ID="chkHobbied" runat="server" RepeatDirection="Horizontal">
                    <asp:ListItem Value="C">Cricket</asp:ListItem>
                    <asp:ListItem Value="F">Football</asp:ListItem>
                </asp:CheckBoxList>
                <input id="hiddenOptionValidatorchkHobbied" name="hiddenOptionValidatorchkHobbied"
                    type="hidden" />
            </td>
        </tr>
        <tr>
            <td>
                Married:
            </td>
            <td>
                <asp:RadioButtonList ID="rbtnMarried" runat="server" RepeatDirection="Horizontal">
                    <asp:ListItem Value="M">Married</asp:ListItem>
                    <asp:ListItem Value="U">Unmarried</asp:ListItem>
                </asp:RadioButtonList>
                <input id="hiddenOptionValidatorrbtnMarried" name="hiddenOptionValidatorrbtnMarried"
                    type="hidden" />
            </td>
        </tr>
        <tr>
            <td>
                &nbsp;
            </td>
            <td>
                <asp:Button ID="btnSubmit" runat="server" Text="Submit" />
            </td>
        </tr>
    </table>

 

Kamal Pratap

I have 6+ years experience in .Net technologies like Asp.Net, C#, WCF, Web Services, SQL Server, Ajax, LinQ. Currently I am working in Netcarrots Loyalty Services as a Software Developer.

Comments

No coments found to display!

Leave a Comment