Adding Error Messages to a ValidationSummary

Validation summaries are nice when you are using the ASP.NET validation controls. It would be also quite handy to add your own validation/error messages (from internal validation or exception handling) to a summary. With a little background knowledge about the ASP.NET validation infrastructure, this is easily possible.

All validation controls implement the IValidator interface and add themselves to the Page.Validators collection at page creation time. IValidator has three members: IsValid, ErrorMessage and Validate(). When validation occurs, the Validate() method of each control is called which in turn sets the IsValid and ErrorMessage property. At render time the ValidationSummary cycles through the Validators collection and looks for controls where IsValid is set to false. If that’s the case, the value of the ErrorMessage property is rendered to the summary.

To add a new error message, you simply have to add an IValidator derived class to the Validators collection (with IsValid = false) and let the summary pick it up. The following small helper class accomplishes that:

// adds an error message to a ValidationSummary control

public class ErrorSummary : IValidator

{

    string _message;

 

    public static void AddError(string message, Page page)

    {

        ErrorSummary error = new ErrorSummary(message);

        page.Validators.Add(error);

    }

 

    private ErrorSummary(string message)

    {

        _message = message;

    }

 

    public string ErrorMessage

    {

        get { return _message; }

        set { }

    }

 

    public bool IsValid

    {

        get { return false; }

        set { }

    }

 

    public void Validate()

    { }

}

You can use the class in your code like that:

catch (Exception ex)

{

    // logging

 

    ErrorSummary.AddError(“error message”, this);

    return;

}

 

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s