ASP.NET Checkbox Validation using jQuery

ASP.NET validation control provides validation on almost all controls out of the box except checkbox or checkboxlist controls. Even when you try to define control to validate property of validation control to a checkboxlist, you will end up getting an error which read as "Control 'CheckBoxList1' referenced by the ControlToValidate property of 'CustomValidator1' cannot be validated". But checkboxes are vital part of a form so we need to have some way to validate it. Thanks to ASP.NET's extensibility, there is one control that provides you full control as how you would like to put together validation rules to validate your form controls.

So today we will use power of jQuery and blend it with custom validation control to perform checkbox validation.

Screenshot:

Code:

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title></title>

<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

<script type="text/javascript">

function CheckValidation(sender, args) {

var selected=$('#CheckBoxList1 input:checked').length;

if (selected < 3) {

args.IsValid = false;

}

else {

args.IsValid = true;

}

}

</script>

</head>

<body>

<form id="form1" runat="server">

<div>

 

<asp:CheckBoxList ID="CheckBoxList1" runat="server">

<asp:ListItem>iPad</asp:ListItem>

<asp:ListItem>iPhone</asp:ListItem>

<asp:ListItem>iPod</asp:ListItem>

<asp:ListItem>iTunes</asp:ListItem>

<asp:ListItem>iCloud</asp:ListItem>

</asp:CheckBoxList>

 

</div>

<asp:CustomValidator ID="CustomValidator1" runat="server"

ClientValidationFunction="CheckValidation"

ErrorMessage="Please Check Atleast 3 Checkboxes" ForeColor="Red"

></asp:CustomValidator><br />

 

<asp:Button ID="Button1" runat="server" Text="Submit"/>

</form>

</body>

</html>