Click here to Skip to main content
15,879,613 members
Articles / Web Development / ASP.NET
Article

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.7K   665   37   8
An article describing how to add errors to the validation summary at runtime

Runtime validation

Introduction

This article first appeared on www.HowToDoThings.com

This article explains how to add error messages to a ValidationSummary at runtime and have the addition of those message set Page.IsValid to False. This technique is useful when you do not know until runtime what constraints should apply to a webform, or when you want to validate against constraints which do not relate directly to a WebControl.

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 IValidator

C#
public class MultiValidator : WebControl,  IValidator
{
}

I then added an ArrayList to hold the error strings, and a method to add an error.

C#
private ArrayList Errors = new ArrayList();

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

When ASP.NET validates a page it enumerates all IValidators within its own Validators property, and called IValidator.Validate(). To determine if the page is valid or not it then checks IValidator.IsValid.

To add custom error messages at runtime I decided to create a static validator class which always returns "false" from IsValidator.IsValid. For each error message in my MultiValidator I could then simply create an instance of one of these validators.

C#
[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 StaticValidator was written, all I needed to do was to add the required IValidator implementations to my MultiValidator class.

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

  1. Set CausesValidation to false on my submit button.
  2. Validate my object.
  3. Call MultiValidator1.AddError() for each error encountered.
  4. Call Page.Validate();
  5. Check Page.IsValid as normal.
Using a ValidationSummary I could then display the broken constraints to the user for rectification.

Using the code

To 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

C#
if (SomeUnusualCondition)
  multiValidator1.AddError("Something unusual is wrong");

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

 
GeneralMultiValidator1 doesn't appear on the webform Pin
eyale30-Apr-07 9:52
eyale30-Apr-07 9:52 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.