views:

226

answers:

1

Question

Is it posible to have the Validation.Validate() method of the Validation Application Block see each parameter of the IParameterCollection supplied by Unity as my custom UserModel?


Background:

I am attempting to use both Unity and the Validation Application Block to validate method parameters.

I would like to be able to denote a method as [RequiresValidation()] and the parameters of that method with the appropriate validation attributes.

So, something like this:

[RequiresValidation()]
public void SaveUser(UserModel user)
{
  // ...
}

public class UserModel
{
  [StringLengthValidator(3, 255)]
  [RegexValidator(@"^[a-zA-Z0-9]${3,255}")]
  public string Name { get; set; }

  [StringLengthValidator(0, 255)]
  [RegexValidator(@"\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b")]
  public string EMail { get; set; }
}

I have created a custom HandlerAttribute that will initiate the call to the validation handler as shown.

public class RequiresValidationAttribute : HandlerAttribute
{
  public override ICallHandler CreateHandler(IUnityContainer container)
  {
    return new ValidationCallHandler();
  }
}

Now, the Validation Handler will attempt to validate each parameter of the method:

public class ValidationCallHandler : ICallHandler
{
  public int Order { get; set; }

  public IMethodReturn Invoke(IMethodInvocation input, GetNextHandlerDelegate getNext)
  {            
    // Validate the method parameters
    ValidateArguments(input.Arguments);

    // Call the method that was intercepted
    return getNext()(input, getNext);
  }

  private static void ValidateArguments(IParameterCollection parameterCollection)
  {
    foreach (var parameter in parameterCollection)
    {
      var results = Validation.Validate(parameter);
      if (results.IsValid) continue;

      // ...
    }

    // ...
  }
}

Problem

The Validation.Validate() method will always return true. Based on my observations, it seems the validation logic is treating the parameter as an object and not my UserModel.


Question

Is it posible to have the Validation.Validate() method of the Validation Application Block see each parameter of the IParameterCollection supplied by Unity as my custom UserModel?

+2  A: 

You will need to use the ValidationFactory instead of the Validation class. When you replace this line:

var results = Validation.Validate(parameter);

With the following line, you can get it to work.

var results =
    ValidationFactory.CreatValidator(parameter.GetType())
        .Validate(parameter);

Good luck.

Steven
I just gave this a try and it worked perfectly. Much appreciated. Thank You.
Paul