|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
IntroductionThis article first appeared on www.HowToDoThings.com This article explains how to add error messages to a One of the requirements when writing www.howtodothings.com was the ability to model object constraints in OCL and then to validate the current page against those constraints. The problem with normal validators is that they are designed to validate individual controls rather than a list of constraints on an object. The approach I took was to create a validator which I can place on any web form and add as many errors to as I required. The first step was to create a WebControl which supported public class MultiValidator : WebControl, IValidator
{
}
I then added an ArrayList to hold the error strings, and a method to add an error. private ArrayList Errors = new ArrayList();
public void AddError(string message)
{
Errors.Add(message);
}//AddError
When ASP.NET validates a page it enumerates all To add custom error messages at runtime I decided to create a static validator class which always returns "false" from [ToolboxItem(false)]
internal class StaticValidator : IValidator
{
private string errorMessage;
#region IValidator
void IValidator.Validate()
{
}//Validate
bool IValidator.IsValid
{
get { return false; }
set { }
}//IsValid
#endregion
public string ErrorMessage
{
get { return errorMessage; }
set { errorMessage = value; }
}//ErrorMessage
}
Now that the #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
Within a webform, I would now
Using the codeTo use the code, simply compile the two provided CS files into a WebControl assembly and then drop a MultiValidator onto your webpage. Errors may be added like so if (SomeUnusualCondition)
multiValidator1.AddError("Something unusual is wrong");
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||