Click here to Skip to main content
6,595,854 members and growing! (18,624 online)
Email Password   helpLost your password?
Web Development » Validation » General     Intermediate

List Validator

By Murray Roke

Validates a ListControl to ensure at least one RadioButton or CheckBox is checked.
C#, Windows, .NET 1.0, .NET 1.1, ASP.NET, Visual Studio, WebForms, Dev
Posted:12 Apr 2005
Updated:24 Jul 2007
Views:48,555
Bookmarked:36 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
9 votes for this article.
Popularity: 4.20 Rating: 4.40 out of 5

1

2

3
4 votes, 44.4%
4
5 votes, 55.6%
5

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

/*

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.

<%@ 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.

<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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Murray Roke


Member
I live in Auckland, New Zealand.

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

And have co-developed an in house CMS system, (who hasn't). And various other web applications.

Before that I developed in ASP 3.0 for several years, with a smattering of Java servlets here and there.
Occupation: Web Developer
Location: New Zealand New Zealand

Other popular Validation articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 25 (Total in Forum: 25) (Refresh)FirstPrevNext
GeneralNicely Done Pinmembermerlin9815:35 25 Jul '07  
Questionassembly File PinmemberAdhoom7:04 13 Dec '06  
AnswerRe: assembly File PinmemberMurray Roke10:57 13 Dec '06  
GeneralHow can i get the assembly File PinmemberAdhoom7:04 13 Dec '06  
GeneralAn idea. Pinmemberturbochris3:51 7 Apr '06  
GeneralRe: An idea. PinmemberMurray Roke1:23 21 Mar '08  
QuestionCan I use CheckBoxList in a Dialog page? PinmemberAlpha Davis14:00 22 Feb '06  
GeneralRe: Can I use CheckBoxList in a Dialog page? PinmemberMurray Roke14:40 22 Feb '06  
Generalgreat but needs a tweak PinmemberJCollum13:21 16 Feb '06  
GeneralRe: great but needs a tweak PinmemberJCollum14:56 16 Feb '06  
GeneralRe: great but needs a tweak PinmemberMurray Roke15:40 16 Feb '06  
Jokehttp://buy-medications-online.ceroline.info/ Pinsusshttp://buy-medications-online.ceroline.info/6:44 4 Dec '07  
GeneralRe: great but needs a tweak Pinmemberaprenot10:58 17 Feb '06  
GeneralRe: great but needs a tweak PinmemberMurray Roke18:08 11 Sep '06  
GeneralRe: great but needs a tweak PinmemberJCollum8:29 22 Jul '07  
GeneralRe: great but needs a tweak PinmemberMurray Roke13:48 22 Jul '07  
GeneralRe: great but needs a tweak PinmemberJCollum9:20 23 Jul '07  
GeneralRe: great but needs a tweak PinmemberJCollum12:00 23 Jul '07  
AnswerRe: great but needs a tweak PinmemberJCollum7:38 24 Jul '07  
GeneralRe: great but needs a tweak PinmemberMiguel Hasse de Oliveira2:11 20 Mar '08  
GeneralRe: great but needs a tweak PinmemberMurray Roke1:38 21 Mar '08  
GeneralValidate a max count checked Pinmembertbaseflug9:00 8 Dec '05  
GeneralRe: Validate a max count checked PinmemberMurray Roke10:11 8 Dec '05  
GeneralRe: C# Code to Validate a max/min count checked Pinmemberdfg fd g14:52 26 Sep '07  
GeneralRe: C# Code to Validate a max/min count checked Pinmemberdfg fd g14:54 26 Sep '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 24 Jul 2007
Editor: Genevieve Sovereign
Copyright 2005 by Murray Roke
Everything else Copyright © CodeProject, 1999-2009
Web22 | Advertise on the Code Project