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

Adding ASP.NET validation at runtime

Rate me:
Please Sign up or sign in to vote.
4.64/5 (6 votes)
4 Mar 20052 min read 83.9K   665   37  
An article describing how to add errors to the validation summary at runtime
using System;
using System.Collections;
using System.ComponentModel;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace DroopyEyes.Web.Controls
{
	public class MultiValidator : WebControl,  IValidator
	{
		#region Members
		private bool isValid = true;
		private string errorMessage = "";
		private ArrayList Errors = new ArrayList();
		private ArrayList Validators = new ArrayList();
		#endregion

		#region IValidator
		void IValidator.Validate()
		{
			isValid = (Errors.Count == 0);
			foreach(string error in Errors)
			{
				StaticValidator validator = new StaticValidator();
				validator.ErrorMessage = error;
				Page.Validators.Add(validator);
				Validators.Add(validator);
			}//foreach errors
		}//Validate

		bool IValidator.IsValid
		{
			get { return isValid; }
			set { isValid = value; }
		}//IsValid
		#endregion

		protected override void OnInit(EventArgs e)
		{
			base.OnInit(e);
			Page.Validators.Add(this);
		}

		protected override void OnUnload(EventArgs e)
		{
			if (Page != null)
			{
				Page.Validators.Remove(this);
				foreach(IValidator validator in Validators)
					Page.Validators.Remove(validator);
			}//Page != null

			base.OnUnload(e);
		}


		public void AddError(string message)
		{
			Errors.Add(message);
		}//AddError



		#region Properties
		[Bindable(true)]
		[Category("Appearance")]
		[DefaultValue("")]
		public string ErrorMessage
		{
			get { return errorMessage; }
			set { errorMessage = value; }
		}//ErrorMessage
		#endregion

	}
}

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 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


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions