There are a few out of the box Visual Studio validators such as asp:RequiredFieldValidator etc, but none of them validate set of checkboxes and whether at least one of the check boxes in a list was checked off. This is quite a common scenario though and here is one of the way to perform such validation using JQuery and a bit of your own JavaScript.
Lets say here is your CheckBoxList on the page:
<asp:CheckBoxList runat=”server” id=”choiceList”>
<asp:ListItem Text=”Choice1″ Value=”Choice1″ />
<asp:ListItem Text=”Other” Value=”Other” />
</asp:CheckBoxList>
Somewhere below you have your RequiredFieldValidator defined:
<asp:CustomValidator ID=”customCheckBoxListValidator” runat=”server” ErrorMessage=”Select at least one choice” ClientValidationFunction=”ValidateOptions” />
The goes my my JavaScript, I retireve all of the checkboxes that belong to my
checkboxlist choiceList and go through all of them verifying whether they’re checked. Just one is required to pass the validation. You can have this script right inside your page or custom control or seal it inside JS file
<script type=”text/javascript”>
ValidateOptions = function(args) {
var options = $(”input[id^=<%=choiceList.ClientID%>]“);
for (i = 0; i < options.length; i++) {
if (options[i].checked) {
args.IsValid = true;
return;
}
}
args.IsValid = false;
}
</script>
Since we used JQuery functions to get a hold of the check box control, you should include the reference to it; I recommend using a reference to google or yahoo library to keep things up to date:
http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js
Yaroslav Pentsarskyy, Microsoft MVP
Blog:
www.sharemuch.com