March 5, 2011

Custom Validator for CheckBoxList Server Control

ASP.NET has no Required Field Validator available for Checkbox List or Checkbox .
Below is the Example to use Custom Validator for checkboxlist which validates that atleast one checkbox should be selected from the list.


ExCustomValidator1.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ExCustomValidator1.aspx.cs" Inherits="ExCustomValidator1"%>


<script language="javascript" type="text/javascript"> 


function CheckAgeGroup(sender, args)
{
     
    var options = document.getElementById('chKAge').getElementsByTagName('input');
    var ischecked=false;
    args.IsValid =false;
    for(i=0;i<options.length;i++)
    {
        var opt = options[i];
        if(opt.type=="checkbox")
        {
            if(opt.checked)
            {
                ischecked= true;
                args.IsValid = true;                
            }
        } 
    }
}


</script>


<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:CheckBoxList ID="chKAge" CellPadding="2" cellspacing="0"  RepeatColumns="2" runat="server"> 
            <asp:ListItem Value="1">2-9</asp:ListItem>
            <asp:ListItem Value="2">10-18</asp:ListItem>
            <asp:ListItem Value="3">19-30</asp:ListItem>
            <asp:ListItem Value="4">30-60</asp:ListItem>
                                        </asp:CheckBoxList>                                     
  <asp:CustomValidator  ClientValidationFunction="CheckAgeGroup" ValidationGroup="Group1" ID="ValidateAge" runat="server" ErrorMessage="Please Select Age Group" > </asp:CustomValidator>  
  <asp:Button ID="btnSubmit" Text ="submit" runat ="server" ValidationGroup =  "Group1" />
    
    </div>
    </form>
</body>
</html>

No comments:

Post a Comment