Sunday, May 04, 2008

Collecting Validation Exceptions

I've been putting some thought into validation in the context of an MVC Framework application. Recently I wrote about using Extension Method Validators as a neat way of expressing validation rules in your domain entities. These validators throw a ValidationException when they trigger.

sutekishopValidationErrors

Now in a user interface we would really like to see all the validation failures for a form. So we need to collect the exceptions as they occur and then continue processing. Here's a neat little Validator class that's simply a collection of Action delegates that executes them when its Validate method is called:

public class Validator : List<Action>
{
  public void Validate()
  {
      StringBuilder message = new StringBuilder();

      foreach (Action validation in this)
      {
          try
          {
              validation();
          }
          catch (ValidationException validationException)
          {
              message.AppendFormat("{0}<br />", validationException.Message);
          }
      }

      if (message.Length > 0)
      {
          throw new ValidationException(message.ToString());
      }
  }
}

You can use it like this:

string property = "";

Validator validator = new Validator
{
  () => property.Label("Property 1").IsRequired(),
  () => property.Label("Property 2").IsRequired(),
  () => property.Label("Property 3").IsRequired()
};

validator.Validate();

Since the 'property' variable is an empty string, each call to IsRequired() will throw a ValidationException. The message of each of these exceptions gets captured and then a single ValidationException will be called with the concatenated messages.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.