Workaround for chekcbox list validation
May 28, 2010 Leave a comment
If you have tried to add a validator like a RequiredFieldValidator to a checkbox list asp control, you will de surprised to discover that that is not possible, and will result in error if you try. To counter this you can do two things extend checkbox list control ore make a custom validator. I chose the second solution, to keep the code to a minimum. Her’s a quick setup. I am taking advantage of OnServerValidate attribute of the CustomValidator control.
<asp:CustomValidator id="CustomCheckboxlistValidator1" runat="server" OnServerValidate="CheckboxlistValidate" ControlToValidate="MjauCheckboxlist " ErrorMessage="One or more checkboxes must be chosen"> </asp:CustomValidator>
CheckboxlistValidate is the name of a javascript function that will hold the validation logic.
<script language="javascript"> function CheckboxlistValidate (oSrc, args) { var checkboxList= document.getElementById("<%=MjauCheckboxlist.ClientID%>"); var InputElements = checkboxList.getElementsByTagName("input"); for (var i = 0; i < InputElements.length; i++) { var input = InputElements[i]; if (input.checked) { args.IsValid = true; return null; } args.IsValid = false; } } </script>
The JavaScript code is pretty simple. checkboxList variable holds the Html element with all checkboxes. From that you can derive all Imput elements and check them if they have been chosen. args.IsValid is used to set validation status. That’s it. One thing to remember thou the javascritp function must have to parameters,… oSrc – objectSource and arg – arguments. That’s about it (c:
Happy coding