Validate ASP.NET CheckBoxList which is inside a DataList Control
Recently someone was facing a problem on validating a CheckBoxList using CustomValidator control. The CheckBoxList was inside of a DataList control.
As for e.g. something like below:
<asp:DataList ID="DataList1" runat="server"> <ItemTemplate> <asp:CheckBoxList ID="CheckBoxList1" runat="server"> <asp:ListItem Text="One" Value="1"></asp:ListItem> <asp:ListItem Text="Two" Value="2"></asp:ListItem> </asp:CheckBoxList> <asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="Please check at least one item." ClientValidationFunction="ValidateCBL"></asp:CustomValidator> </ItemTemplate> </asp:DataList>
Here’s the code that does the job.
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script> <script type = "text/javascript"> function ValidateCBL(source, args) { var cblist= $(source).parent().find("table[id$='_CheckBoxList1']"); if (cblist.length==0 || cblist.find('input:checkbox:checked').length > 0) { args.IsValid = true; } else { args.IsValid = false; } } </script>
It is using jQuery to do get the control and finding if anything is checked.
$(source).parent() will get parent DOM element of the CustomValidator control that fired the ValidateCBL function. And then it finds any table that has an id ending with _CheckBoxList1. It’s because by default CBL is rendered as and table. When inside of a databound control, the asp.net will, by default, change the id to something like Ctl00_something_CheckBoxList1.
Then it checks if there is at lease one checkbox checked, if so then set args.IsValid=true for that CustomValidator else it will set it to false.
The above code isn’t specific to CBL inside of a DataList only. It would work for most of the DataBoundControls like GridView, Repeater, ListView, etc.
Hope this helps.