Saturday, May 09, 2009

Validating checkbox list in asp.net using JQuery

ASP.net does not provide in built support to validate a checkbox list. We have to rely on custom javascript to verify if at least one checkbox in the list is checked.

Since we cannot add a validator to the checkbox list, I usually put a dummy textbox on the form and add a custom validator to that textbox.


<asp:CheckBoxList ID="cblLostDescription" runat="server" RepeatDirection="Horizontal" TabIndex="14">
<asp:ListItem Value="L">Lost/Stolen</asp:ListItem>
<asp:ListItem Value="D">Destroyed</asp:ListItem>
<asp:ListItem Value="M">Damaged</asp:ListItem>
<asp:ListItem Value="O">Other</asp:ListItem>
</asp:CheckBoxList>
<asp:CustomValidator ID="custValDescrption" runat="server" ErrorMessage="Property Description is required"
Display="Dynamic" ControlToValidate="txtPropertyDummy"
ClientValidationFunction="ValidatePropertyDescription" ValidateEmptyText="true"></asp:CustomValidator>
<asp:TextBox runat="server" ID="txtPropertyDummy" Width="1px" Style="display: none"></asp:TextBox>


Following is the client side validation function that we added to the custom validator. If we take a look at the rendered html, all The checkboxes in our list do not have the same id or name attribute.But all the ids start with the id we gave to the checkbox list. We can use JQeury to select the group of checkboxes whose ids start with a given text , then loop through the set and verify if at least one checkbox is checked. Make sure you have a reference to the JQuery script file on your asp.net page.


//Using JQuery, select all the checkboxes whose id begins with the
//asp.net checkbox list server control's ID.
function ValidatePropertyDescription(sender, args) {
var chkGroup = $("input[id^=<%=cblLostDescription.ClientID%>]");
//Loop through the set returned by JQuery
for (i = 0; i < chkGroup.length; i++) {
if (chkGroup[i].checked) {
args.IsValid = true;
return;
}
}
args.IsValid = false;
}

Digg It! Add to del.icio.us Stumble This

0 Comments: