3
votes

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.

1
if you don't have to use jquery, maybe this can help. the sample is textbox, but you can use it for checkboxlist. msdn.microsoft.com/en-us/library/… - Ray Cheng
can you post your html mark up code? or an example? it's probably something obvious like syntax error. - Ray Cheng
I used the same code.the custom vaidator works fine.The other code is in question.For testing I just returned always false.It should not validate in this case but it is getting validated. - Krishnanunni Jeevan

1 Answers

1
votes

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>