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.


<%@ 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;
        var opt = options[i];
                ischecked= true;
                args.IsValid = true;                


<html xmlns="" >
<head runat="server">
    <title>Untitled Page</title>
    <form id="form1" runat="server">
        <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: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" />

No comments:

Post a Comment