We can Validate CheckboxList using the CustomValidator on Client side and server-side as well.
Our approach here will be validating the checkboxlist on server-side.
1. Add the CheckboxList with some items as below.
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
<asp:ListItem>A</asp:ListItem>
<asp:ListItem>B</asp:ListItem>
<asp:ListItem>C</asp:ListItem>
</asp:CheckBoxList>
2. Add a CustomValidator Control from the toolbox.
I have added a OnServerValidate event which will validate the checkboxlist on server side on button click.
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please select alteast one option" OnServerValidate="CustomValidator1_ServerValidate" ></asp:CustomValidator>
3. Add a Button to Check the Validations are working.
<asp:Button ID="Button1" runat="server" Text="Button" />
4. the c# code for validating the list.
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
int count = 0;
foreach (ListItem item in CheckBoxList1.Items)
{
if (item.Selected)
{
count++;
break;
}
}
if (count > 0)
args.IsValid = true;
else
args.IsValid = false;
}
Our approach here will be validating the checkboxlist on server-side.
1. Add the CheckboxList with some items as below.
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
<asp:ListItem>A</asp:ListItem>
<asp:ListItem>B</asp:ListItem>
<asp:ListItem>C</asp:ListItem>
</asp:CheckBoxList>
2. Add a CustomValidator Control from the toolbox.
I have added a OnServerValidate event which will validate the checkboxlist on server side on button click.
<asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please select alteast one option" OnServerValidate="CustomValidator1_ServerValidate" ></asp:CustomValidator>
3. Add a Button to Check the Validations are working.
<asp:Button ID="Button1" runat="server" Text="Button" />
4. the c# code for validating the list.
protected void CustomValidator1_ServerValidate(object source, ServerValidateEventArgs args)
{
int count = 0;
foreach (ListItem item in CheckBoxList1.Items)
{
if (item.Selected)
{
count++;
break;
}
}
if (count > 0)
args.IsValid = true;
else
args.IsValid = false;
}