Mvc, validate controller action input

This post will not be about another validation framework, as there is allready many good once out there. Instead I will talk about how to simplify the use of a validation framework in a asp.net mvc application.

As I have told you before I like to keep my controller action simple and clean. Any row of code I can take away, I will. So a few weeks back when I was playing around abit, I came up with the idee of putting the acctual validation process in a base controller, much like they way I did with the captcha validation that I wrote about here.

I created a attribute to put on the action where I need to validate a input parameter. The attribute defines what parenter(s) to validate and what validator to use. The validator has to implement the interface IValidator. That interface looks like this:

public interface IValidator
{
    ValidationSummery Validate(object @object);
}

Here you are free to use whatever validation library you find best.

The validation attribute looks like this:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = true, 
                Inherited = false)]
public class EntityValidationAttribute : Attribute
{
    public EntityValidationAttribute(Type validatorType, 
                   params string[] parametersToValidate)
    {
        Validator = validatorType.GetConstructor(
                new Type[0]).Invoke(new object[0]) as IValidator;
        Parameters = parametersToValidate;
    }

    public string[] Parameters { get; private set; }
    public IValidator Validator { get; private set; }
}

Now  I can just check for this attribute in the "OnActionExecuting" method on my base controller and add errors to the model state if there is any. Now I can validate my input with only 1 line of code, like this:

[EntityValidation(typeof(Validator), "comment")]
public ActionResult Save([Bind(Exclude = "Children,Added,Item", 
                           Prefix = "comment")]Comment comment)
{
    if (ModelState.IsValid)
        _commentService.AddComment(comment);
    //Action logic
}

 You can download the source code for this code base here. Feel free to post any sugestions or any feedback.

Shout it
kick it on DotNetKicks.com

Comments

Add comment

Name:

Mail:

Website:

Comment:


<< [1] >>
    << [1] >>