Every ASP.NET developer needs validation on CheckBoxList that can be one of these two:
- Check for RequiredField
- Check for Maximum Selection Limit
Check for RequiredField
I will be using JQuery to interecept the click event of each single Checkbox inside the CheckBoxList and then update a hidden TextBox control which has a RequiredFieldValidator associated to it, when a CheckBox is clicked.
When all CheckBoxes were unselected, the hidden TextBox would have nothing in it which makes the RequiredFieldValidator throws a JavaScript message on Submit.
Listing – 1 : CheckBoxList
<asp:CheckBoxList ID="cblBusinessType" runat="server" CssClass="checkbox" ValidationGroup="VGEdit">
</asp:CheckBoxList>
<asp:Label ID="Label12" runat="server" Text="Select up to 3 Business Types" CssClass="label_black"></asp:Label>
<asp:TextBox ID="txtCheckbox" runat="server" ValidationGroup="testGroup" style='display: none;'/>
<asp:RequiredFieldValidator ID="valCheckboxList" Display="Dynamic"
ErrorMessage="At least one business type must be selected"
runat="server" ControlToValidate="txtCheckbox"
ValidationGroup="VGEdit" EnableClientScript="true" CssClass="ErrorLabel_10"
SetFocusOnError="true"/>
Listing – 2 : jQuery Script for RequiredFieldValidator
<script type="text/javascript">
$(function() {
function checkBoxClicked() {
//Get the total of selected CheckBoxes
var n1 = $("#<%= cblBusinessType.ClientID %> input:checked").length;
//Set the value of the txtCheckbox control
$("input:#<%= txtCheckbox.ClientID %>").val(n1 == 0 ? "" : n1);
}
//intercept any check box click event inside the #list Div
$("#<%= cblBusinessType.ClientID %> :checkbox").click(checkBoxClicked);
});
</script>
Check for Maximum Selection Limit
We also often need to check that user can select only n items from the checkboxlist. so for that I have anothe jQuery script that help the developer to restrict the user from selection after he reach the max limit.
Listing – 3 : jQuery Script for Maximum Selection Limit
<script type="text/javascript" language="javascript">
//Count the Total Selection in CheckBoxList - BusinessType
$('#<%= cblBusinessType.ClientID %>').find('input:checkbox').click(function()
{
var totCount=0;
jQuery('#<%= cblBusinessType.ClientID %>').find("input:checkbox").each(function() {
if (jQuery(this).attr("checked"))
{
totCount++;
}
});
if(totCount > 3)
{
alert("Select up to 3 Business Types only...");
return false;
}
return true;
});
</script>
Here in this function I have counted each selected checkbox by using jQuery selector each time user check/uncheck the checkbox. once the count goes beyond the limit flag the error message to user to remind that you have crossed the limit.
Hope this will Help
Jay Ganesh

23.052108
72.533442