# Tuesday, November 29, 2005

Below is the C# code for an ASP.NET required validator web control that requires a specified set of controls to be all populated, or all empty.  It inherits from the RequiredFieldValidator ASP.NET class, so it essentially works the same way, it just treats the set of controls you specify as if they were one control (in the sense of requirement).

To use this code, I'd recommend placing it into your own library (because you'll create your own to add to this one -- it's easy!) of custom web controls (in VS.NET, a Class Library), and then add your library as a reference in your web project(s). In your web project, to specify the controls that are part of the set, add their names to the ControlNames collection:



  • I was unable to get the design mode attribute "TypeConverter(typeof(CollectionConverter))" to work correctly in Visual Studio.NET in design mode.  It is not necessary functionality to use this validator.  If anyone can get the design mode CollectionConverter working, I'd love to see your revision (I honestly haven't spent much time on it). 
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections.Specialized;
using System.ComponentModel;

namespace Custom

	/// Required validator that validates a set of controls requiring that they are
	/// all populated or all empty
	public class AllOrNothingRequiredValidator : RequiredFieldValidator

		private StringCollection _scControlNames;
		public AllOrNothingRequiredValidator() : base()
			_scControlNames = new StringCollection();
			EnableClientScript = false;
			Description("The controls to validate."),
		public StringCollection ControlNames
			get { return _scControlNames; }
			set { _scControlNames = value; }

		protected override bool ControlPropertiesValid()
			return true;

		protected override bool EvaluateIsValid()

			Control control;
			int iCounter = 0;
			string[] aryValues = new string[_scControlNames.Count];

			foreach (string sControlName in _scControlNames)
				control = Page.FindControl(sControlName);

				//make sure control exists & is validatable
				CheckControlValidationProperty(sControlName, "ControlNames");

				//add value to array to eval later
				aryValues[iCounter] = GetValidationProperty(control).GetValue(control).ToString();



			//eval if all are empty or populated
			bool bAllEmpty = true;
			bool bAllPopulated = true;

			foreach (string sValue in aryValues)

				if (sValue.Trim().Length == 0)
					bAllPopulated = false;
					bAllEmpty = false;


			return bAllEmpty || bAllPopulated;



If you found this post helpful, please "Kick" it so others can find it too:

kick it on DotNetKicks.com
.NET | ASP.NET | C_Sharp