Reputation: 1759
Is it possible to add a custom validation function to jquery validate plugin for ASP.NET CheckBox list?I am using jquery plugin to validate all controls at client side.It works perfectly with normal inputs like textbox,dropdown list etc.For some reason it is not working with Checkboxlist.In pure html checkboxlist becomes a table with html input checkboxes in it.I wrote a custom function to check whether any of the checkboxes is checked and added it to the jquery validate but for some reason the function is not getting called.
jQuery.validator.addMethod('cb_selectone', function (value, element) {
return false;
}, 'Please select at least one option');
I tried returning false all the time but still the form is validated successfully.Any help would be appreciated.
Upvotes: 3
Views: 4060
Reputation: 12586
Here's one approach but not using jquery.validate.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<script type="text/javascript" src="Scripts/jquery-1.8.0.js"></script>
<script type="text/javascript">
function cb_selectone(src, args) {
var items = $("input[name^='cblTest']");
for (i = 0; i < items.length; i++) {
if ($(items[i]).is(":checked")) {
args.IsValid = true;
return;
}
}
args.IsValid = false;
}
</script>
<body>
<form id="form1" runat="server">
<div>
<asp:CheckBoxList runat="server" ID="cblTest">
<asp:ListItem Text="Test A" Value="A"></asp:ListItem>
<asp:ListItem Text="Test B" Value="B"></asp:ListItem>
</asp:CheckBoxList>
<asp:CustomValidator ErrorMessage="Please select at least one.<br/>" ClientValidationFunction="cb_selectone" runat="server" />
<asp:Button runat="server" ID="btnTest" Text="Submit" />
</div>
</form>
</body>
</html>
Upvotes: 1