Click here to Skip to main content
15,881,938 members
Articles / Web Development / ASP.NET
Article

List Validator

Rate me:
Please Sign up or sign in to vote.
4.40/5 (9 votes)
24 Jul 2007MIT 90.7K   39   24
Validates a ListControl to ensure at least one RadioButton or CheckBox is checked.

Objective

This article has two goals.

  1. Implement a good ListValidator to validate whether at least one item in a CheckBoxList or RadioButtonList has been checked.
  2. Demonstrate a fully functional validator.

Common omissions / problems

Many validators seem to fall down in one area or another. This control is an attempt to demonstrate how a complete validator should look. As this is my first article, I'm sure I'll miss something or lots of things. Please let me know and I'll try to keep it up-to-date. Here are a few common problems. My example shows how to implement these features.

  • Validators that don't implement client script.
  • Validators that don't implement EnableClientScirpt="false".
  • Validator client scripts that don't work with multiple validators on a page.

Here's the code

C#
/*

Author:        Murray Roke
Email:        murray@roke.co.nz

Features
 - ClientScript        works.
 - EnableClientScript    works.
 - Multiple Validators    works.

Change Log:
2006-02-17
Implemented fix for javascript validation 
of radio buttons.. Thanks to JCollum from TheCodeProject 

*/
using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CompanyName.Web.Controls.Validators
{
    /// <summary>
    /// Validates if at least one item in a ListControl is checked.
    /// </summary>
    /// <remarks>
    /// Original javascript code came from this example, but 
    /// I've improved upon it. 
    /// to get multiple validators on a page working correctly.
    /// http://www.dotnetjunkies.com/
    /// Article/ECCCD6A6-B312-41CB-87A1-10BB5D641D20.dcik
    /// </remarks>
    [DefaultProperty("ErrorMessage")] // make the error message the default 
                                      // property to edit at design time 
                                      // for those using gui editor
    public class ListControlRequiredFieldValidator : BaseValidator 
    {
        /// <summary>
        /// Validator Requirement
        /// </summary>

        /// <returns>True if dependencies are valid.</returns>
        protected override bool ControlPropertiesValid()
        {
            Control controlToValidate = 
                FindControl(ControlToValidate) as ListControl;
            return (controlToValidate != null);
        }

        /// <summary>
        /// Validator Requirement
        /// </summary>
        /// <returns>true if ControlToValidate 
        /// has one item or more selected</returns>

        protected override bool EvaluateIsValid() 
        {
            return this.EvaluateIsChecked();
        }

        /// <summary>
        /// Return true if an item in the list is selected.
        /// </summary>
        /// <returns>true if ControlToValidate 
        ///      has one item or more selected</returns>
        protected bool EvaluateIsChecked() 
        {
            ListControl listToValidate = 
                ((ListControl) this.FindControl(this.ControlToValidate));

            foreach( ListItem li in listToValidate.Items ) 
            {
                if ( li.Selected == true ) 
                    return true;
            }
            return false;
        }

        /// <summary>

        /// Pre Render
        /// </summary>
        /// <param name="e"></param >
        protected override void OnPreRender( EventArgs e )
        {
            System.Web.HttpContext.Current.Trace.Write(
                                         "Override OnPreRender");
            if(this.DetermineRenderUplevel() && this.EnableClientScript)
            {
                Page.ClientScript.RegisterExpandoAttribute(this.ClientID, 
                    "evaluationfunction", "ListItemVerify");
                Page.ClientScript.RegisterExpandoAttribute(this.ClientID, 
                    "minimumNumberOfSelectedCheckBoxes", "1"); 
                    //TODO: imporove to allow variable number.
                this.RegisterClientScript();
            }
            else
            {
                this.Attributes.Remove("evaluationfunction");
            }
            base.OnPreRender( e );
        }

        /// <summary>
        /// Register the client script.
        /// </summary>

        protected void RegisterClientScript() 
        {
            string script = @"

            <script language=""javascript"">
            function ListItemVerify(val) 
            {
                var control = 
                    document.getElementById(val.controltovalidate);
                var minimumNumberOfSelectedCheckBoxes = 
                    parseInt(val.minimumNumberOfSelectedCheckBoxes);
                var selectedItemCount = 0;
                var liIndex = 0;
                var currentListItem = 
                    document.getElementById(control.id + 
                    '_' + liIndex.toString());
                while (currentListItem != null)
                {
                    if (currentListItem.checked) selectedItemCount++;
                    liIndex++;
                    currentListItem = 
                        document.getElementById(control.id + 
                        '_' + liIndex.toString());
                }
                return selectedItemCount >= 
                    minimumNumberOfSelectedCheckBoxes;
            }
            </script>
            ";

            this.Page.ClientScript.RegisterClientScriptBlock(
                typeof(ListControlRequiredFieldValidator), 
                "ListRequiredValidator_Script",script);
        }
    }
}

Example usage

Register the library.

ASP.NET
<%@ Register TagPrefix="CompanyName" 
    NameSpace="CompanyName.Web.Controls.Validators"
    Assembly="CompanyName.Web" %>

Create the validator. Imagine that the CheckBoxList you wish to validate is called MyCheckList.

HTML
<CompanyName:ListControlRequiredFieldValidator
    ControlToValidate="MyCheckList" 
    display="Dynamic" 
    ErrorMessage="Select at least one item" 
    EnableClientScript="true" 
    runat="Server">
    Tick at least one box
</CompanyName:ListControlRequiredFieldValidator>

History

  • 12 April, 2005 -- Original version posted
  • 17 February, 2006 -- Updated
  • 24 July, 2007 -- Updated

License

This article, along with any associated source code and files, is licensed under The MIT License


Written By
Web Developer
New Zealand New Zealand
I live in Auckland, New Zealand.

I've been developing ASP.net applications in C# since the .net framework was in beta.


Before that I developed in ASP 3.0 for several years, with a smattering of Java servlets here and there.

Comments and Discussions

 
GeneralNicely Done Pin
merlin98125-Jul-07 4:35
professionalmerlin98125-Jul-07 4:35 
Questionassembly File Pin
Adhoom13-Dec-06 6:04
Adhoom13-Dec-06 6:04 
AnswerRe: assembly File Pin
Murray Roke13-Dec-06 9:57
Murray Roke13-Dec-06 9:57 
QuestionHow can i get the assembly File Pin
Adhoom13-Dec-06 6:04
Adhoom13-Dec-06 6:04 
GeneralAn idea. Pin
turbochris7-Apr-06 2:51
turbochris7-Apr-06 2:51 
GeneralRe: An idea. Pin
Murray Roke21-Mar-08 0:23
Murray Roke21-Mar-08 0:23 
QuestionCan I use CheckBoxList in a Dialog page? Pin
Taichung22-Feb-06 13:00
Taichung22-Feb-06 13:00 
GeneralRe: Can I use CheckBoxList in a Dialog page? Pin
Murray Roke22-Feb-06 13:40
Murray Roke22-Feb-06 13:40 
Generalgreat but needs a tweak Pin
JCollum16-Feb-06 12:21
JCollum16-Feb-06 12:21 
GeneralRe: great but needs a tweak Pin
JCollum16-Feb-06 13:56
JCollum16-Feb-06 13:56 
GeneralRe: great but needs a tweak Pin
Murray Roke16-Feb-06 14:40
Murray Roke16-Feb-06 14:40 
GeneralRe: great but needs a tweak Pin
aprenot17-Feb-06 9:58
aprenot17-Feb-06 9:58 
GeneralRe: great but needs a tweak Pin
Murray Roke11-Sep-06 17:08
Murray Roke11-Sep-06 17:08 
GeneralRe: great but needs a tweak Pin
JCollum22-Jul-07 7:29
JCollum22-Jul-07 7:29 
GeneralRe: great but needs a tweak Pin
Murray Roke22-Jul-07 12:48
Murray Roke22-Jul-07 12:48 
GeneralRe: great but needs a tweak Pin
JCollum23-Jul-07 8:20
JCollum23-Jul-07 8:20 
GeneralRe: great but needs a tweak Pin
JCollum23-Jul-07 11:00
JCollum23-Jul-07 11:00 
AnswerRe: great but needs a tweak Pin
JCollum24-Jul-07 6:38
JCollum24-Jul-07 6:38 
GeneralRe: great but needs a tweak Pin
Miguel Hasse de Oliveira20-Mar-08 1:11
professionalMiguel Hasse de Oliveira20-Mar-08 1:11 
Here's another way to go... my way Big Grin | :-D

This script allows the validation of DropDownList controls.

function ListItemVerify(val) {<br />
  if (typeof(val.controltovalidate) == "string") {<br />
    var selectedCount = 0, control = document.getElementById(val.controltovalidate);<br />
        <br />
      if (control.tagName.toLowerCase() == "select") {<br />
        selectedCount = new Number(control.selectedIndex > -1);<br />
      }<br />
      else for (i = 0;; i++) {<br />
        if ((currentListItem = document.getElementById(control.id + '_' + i.toString())) == null) break;<br />
          selectedCount += new Number(currentListItem.checked);<br />
        }<br />
        return selectedCount >= parseInt(val.minimumNumberOfSelectedCheckBoxes);<br />
    }<br />
    return true;<br />
}


Hope this proofs useful.

Miguel Hasse
GeneralRe: great but needs a tweak Pin
Murray Roke21-Mar-08 0:38
Murray Roke21-Mar-08 0:38 
GeneralValidate a max count checked Pin
tbaseflug8-Dec-05 8:00
tbaseflug8-Dec-05 8:00 
GeneralRe: Validate a max count checked Pin
Murray Roke8-Dec-05 9:11
Murray Roke8-Dec-05 9:11 
GeneralRe: C# Code to Validate a max/min count checked Pin
esteban8226-Sep-07 13:52
esteban8226-Sep-07 13:52 
GeneralRe: C# Code to Validate a max/min count checked Pin
esteban8226-Sep-07 13:54
esteban8226-Sep-07 13:54 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.