Related Posts Plugin for WordPress, Blogger...

About

Follow Us

Thursday, 12 February 2015

Introduction: 

In this article we will learn how to validate CheckBoxList control i.e. to ensure at least one item is selected in the CheckBoxList. It can be done in many ways but I’ll use CustomValidator control andJavaScript to validate.


Implementation: Let's understand by a practical example.

In the <HEAD> tag of the design page(.aspx) create the JavaScript function to validate the CheckBoxList.
 <script type = "text/javascript">
        function validateCheckBoxList(source, args) {
            var chkListModules = document.getElementById('<%= chkCity.ClientID %>');
            var chkListinputs = chkListModules.getElementsByTagName("input");
            for (var i = 0; i < chkListinputs.length; i++) {
                if (chkListinputs[i].checked) {
                    args.IsValid = true;
                    return;
                }
            }
            args.IsValid = false;
        }
    </script>
In the <Body> tag place a CheckBoxList, a Label control, a Button control and a CustomValidator control. In the CheckBoxList add some items as shown below:

    <fieldset style="width:400px">
            <legend>Validate CheckBoxList</legend> 
        <asp:CheckBoxList ID="chkCity" runat="server" AutoPostBack="true" RepeatColumns="2">
            <asp:ListItem>Delhi</asp:ListItem>
            <asp:ListItem>Chandigarh</asp:ListItem>
            <asp:ListItem>Ambala</asp:ListItem>
            <asp:ListItem>Panchkula</asp:ListItem>
        </asp:CheckBoxList> 

                <asp:Label ID="lblStatus" runat="server" Text=""></asp:Label>
         <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please select at least one skills." ClientValidationFunction = "validateCheckBoxList" Display="static" ForeColor="Red"></asp:CustomValidator>
        <asp:Button ID="btnSubmit" runat="server" Text="Submit"
            onclick="btnSubmit_Click" />  

        </fieldset>

C#.Net Code to validate CheckBoxList using JavaScript
In the code behind file(.aspx.cs) write the code as:

protected void btnSubmit_Click(object sender, EventArgs e)
    {
        lblStatus.Text="Validation successful";
    }

VB.Net Code to validate CheckBoxList using JavaScript
In the code behind file(.aspx.vb) write the code as:

Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) HandlesbtnSubmit.Click
        lblStatus.Text = "Validation successful"

    End Sub

0 comments:

Post a Comment