Click here to Skip to main content
15,894,330 members
Articles / Web Development / ASP.NET

Template Based Multiple Control Validator

Rate me:
Please Sign up or sign in to vote.
4.82/5 (10 votes)
25 Mar 2009CPOL3 min read 39.2K   740   30  
A templated server control that allows us to validate multiple controls with the same validation controls
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing.Design;
using System.Security.Permissions;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel.Design;
using ValidationAggregator;

namespace ValidationAggregator
{
	[
		AspNetHostingPermission(SecurityAction.Demand,
			Level = AspNetHostingPermissionLevel.Minimal),
		AspNetHostingPermission(SecurityAction.InheritanceDemand,
			Level = AspNetHostingPermissionLevel.Minimal),
		Designer(typeof(ValidationTemplateDesigner)),
		DefaultProperty("Validators"),
		ToolboxData("<{0}:ValidationTemplate runat=\"server\"></{0}:ValidationTemplate>")
	]
	public class ValidationTemplate : CompositeControl
	{

		#region Fields

		private ITemplate _validators;
		private List<ControlDesc> _controlsToValidate;
		private string _defaultValidationGroup;
		private bool _forceValidationGroup;

		#endregion

		#region Properties

		[
			Browsable(false),
			PersistenceMode(PersistenceMode.InnerProperty),
			DefaultValue(typeof(ITemplate), ""),
			Description("Control template"),
			TemplateContainer(typeof(ValidationTemplate))
		]
		public virtual ITemplate Validators
		{
			get
			{
				return _validators;
			}
			set
			{
				_validators = value;
			}
		}


		[
			Category("Behavior"),
			Description("The controls collection"),
			DesignerSerializationVisibility(DesignerSerializationVisibility.Content),
			Editor(typeof (CollectionEditor), typeof (UITypeEditor)),
			PersistenceMode(PersistenceMode.InnerProperty)
		]
		public List<ControlDesc> ControlsToValidate
		{
			get
			{
				if (_controlsToValidate == null)
					_controlsToValidate = new List<ControlDesc>();

				return _controlsToValidate;
			}
		}



		[
			Category("Behavior"),
			DefaultValue(""),
			Description("Use this validation group if the control didn't specify")
		]
		public string DefaultValidationGroup
		{
			get { return _defaultValidationGroup; }
			set { _defaultValidationGroup = value; }
		}

		[
			Category("Behavior"),
			DefaultValue("false"),
			Description("Override the validation group of all controls. If Default validation is empty this will clean the validatin group.")
		]
		public bool ForceValidationGroup
		{
			get { return _forceValidationGroup; }
			set { _forceValidationGroup = value; }
		}


		#endregion

		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);
			Page.InitComplete += OnPageInitComplete;
		}

		private class CtrlsContainer : WebControl
		{
			
		}

		protected void OnPageInitComplete(object sender, EventArgs args)
		{
			if (_validators == null || _controlsToValidate == null)
				return;

			foreach (ControlDesc ctrlDesc in _controlsToValidate)
			{
				Control ctrl = NamingContainer.FindControl(ctrlDesc.CID);

				int idx = ctrl.Parent.Controls.IndexOf(ctrl);

				CtrlsContainer cnt = new CtrlsContainer();

				_validators.InstantiateIn(cnt);

				PrepareValidators(cnt, ctrlDesc, null);

				ctrl.Parent.Controls.AddAt(idx + 1, cnt);
			}
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="control"></param>
		/// <param name="desc"></param>
		/// <param name="validationGroup">It take precedence if is not null</param>
		private void PrepareValidators(Control control, ControlDesc desc, string validationGroup)
		{
			foreach (Control ctrl in control.Controls)
			{
				if (ctrl is BaseValidator)
				{
					BaseValidator val = (BaseValidator)ctrl;

					val.ID = "";	// we let the container generate the ids
					val.ControlToValidate = desc.CID;
					val.Text = string.Format(val.Text, desc.Label);
					val.ErrorMessage = string.Format(val.ErrorMessage, desc.Label);

					if (string.IsNullOrEmpty(val.ValidationGroup) || _forceValidationGroup) 
						val.ValidationGroup = _defaultValidationGroup;

					if (validationGroup != null)
						val.ValidationGroup = validationGroup;
				}

				PrepareValidators(ctrl, desc, validationGroup);
			}
		}
		
		/// <summary>
		/// Used by the validator
		/// </summary>
		public Control GetValidators(ControlDesc ctrlDesc, string validationGroup)
		{
			CtrlsContainer cnt = new CtrlsContainer();

			_validators.InstantiateIn(cnt);

			PrepareValidators(cnt, ctrlDesc, validationGroup);

			return cnt;
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Algeria Algeria
Fascinated by good architectures, well thought classes and clean code. I work as a software developer since 2004.

Comments and Discussions