Sometimes you want to force users to make at least one selection in a CheckBoxList.
The problem is that it’s easier said than done, because the RequiredFieldValidator can’t be linked to a CheckBoxList control.
Most likely, you would prefer to do client-side validation as well, right?
I have come across many examples on the web on how to do this, but most of them fall short one way or another.
By adapting and combining the examples, I have come up with the following by using jquery:
<script src="jquery-1.3.2.js" type="text/javascript"></script>
<script type='text/javascript'>
ValidateChecked = function(oSrc, args) {
var n = $("#pnlBoxes input:checked").length;
args.IsValid = (n > 0);
}
</script>
Above is the function that is called by the CustomValidator, i.e. the property of the Validator’s ClientValidationFunction in the code below. I use the jquery Class selector because it is much easier than trying to figure out the rendered ID of the generated web part html.
The Code selects all CheckBoxes which are checked in the Panel and checks the length of the collection, if it’s 0 nothing was checked, so args.IsValid is false etc etc.
<asp:Panel ID="pnlBoxes" runat="server">
<asp:CheckBoxList ID="cbList1" runat="server">
<asp:ListItem>Zero</asp:ListItem>
<asp:ListItem>One</asp:ListItem>
<asp:ListItem>Two</asp:ListItem>
</asp:CheckBoxList>
<asp:CustomValidator ID="CustomValidator1" runat="server"
ClientValidationFunction="ValidateChecked"
ErrorMessage="Just Check something!!" Display="Dynamic" ></asp:CustomValidator>
</asp:Panel>
I used this code in a SharePoint environment in a web part which was rendered entirely through code, thus the use of an asp:Panel instead of a Div.

0 comments:
Post a Comment