Sunday, August 18, 2019

HOW TO VALIDATE CHECKBOXLIST USING JAVASCRIPT IN ASP.NET(C#, VB)

Introduction
Now in this article I am going to explain with example how to validate CheckBoxList control i.e. to ensure at least one item is selected in the CheckBoxList. I am using CustomValidatorcontrol and JavaScript to validate.

checkbox validation using javascript in asp.net


Implementation: Let's understand by an 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('<%= cblCourses.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:160px">
     <legend>Select your skills</legend> 
        <asp:CheckBoxList ID="cblCourses" runat="server" RepeatColumns="2">
            <asp:ListItem>Asp.net</asp:ListItem>
            <asp:ListItem>C#</asp:ListItem>
            <asp:ListItem>VB</asp:ListItem>
            <asp:ListItem>WCF</asp:ListItem>
            <asp:ListItem>Jquery</asp:ListItem>
            <asp:ListItem>JavaScript</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 ObjectByVal e As System.EventArgsHandles btnSubmit.Click
        lblStatus.Text = "Validation successful"
    End Sub

No comments:

Post a Comment

No String Argument Constructor/Factory Method to Deserialize From String Value

  In this short article, we will cover in-depth the   JsonMappingException: no String-argument constructor/factory method to deserialize fro...