Posts Tagged ‘fluentvalidation’

Automatic Fluent Validation Integration into ASP.NET MVC with MvcTurbine.FluentValidation

Monday, May 24th, 2010

I’m a big fan of Fluent Validation, a .Net library written by Jeremy Skinner that makes validation easy and understandable.  If you’ve never seen it, here’s a quick example that should explain it:

public class LoginInputModelValidator : AbstractValidator<LoginInputModel>{
   public LoginInputModelValidator() {
      RuleFor(x=>x.Email).NotEmpty();
      RuleFor(x=>x.Password).NotEmpty();
   }
}

That’s all there is to validating a login form, at least to the point to making sure the email and password were both entered.  See how easy that is?  But the thing is… how do you use it with ASP.NET MVC2?  How do you make its use seamless with the framework?

Well, like most, I started with Jeremy Skinner’s post on MVC2 integration.  He explains how to create your own IValidatorFactory and what code to enter in your global.asax file.  Great help, but couldn’t it be easier?  Do I really want to copy bits of code here and there in each MVC project?  What if I switch IoC containers?  It works, but it didn’t feel like a complete solution to me.

So… I put it on myself to come up with the solution I wanted.  I’m also a big fan of MVC Turbine, a project that integrates IoC throughout your MVC application (which is essential).  MVC Turbine offers the concept of a “blade” that lets you inject code into the startup and the setup of your favorite IoC container.  Essentially, it gives you one place to inject functionality that can then be used throughout your application.  Functionality like… implementing Fluent Validation into your MVC application!

MvcTurbine.FluentValidation

My solution is MvcTurbine.FluentValidation, and the source and binary can be found at here on GitHub.  In order to use it to automatically validate your MVC app, you’ll need to do the following:

1.)  Setup your ASP.NET MVC application to use MVC Turbine (which you should do anyway).

2.)  Add a reference to MvcTurbine.FluentValidation.dll.

That’s it.  Really, that’s it.  By adding MvcTurbine.FluentValidation.dll to your application. MVC Turbine will add the FluentValidationBlade to your application startup.  That blade will scan your project for validators, create an implementation of the IValidatorFactory using your preferred IoC container, create an model validator provider, and incorporate everything into the application.  And to top it all off, it will instantiate your validators through your IoC container, giving you the ability to add dependencies like this:

public class LoginInputModelValidator : AbstractValidator{
   public LoginInputModelValidator(IMembershipService membershipService) {
      RuleFor(x=>x.Email).NotEmpty();
      RuleFor(x=>x.Password).NotEmpty();
      RuleFor(x=>x.Email).CheckThatThisIsAValidEmail(membershipService);
      RuleFor(x=>x.Password).CheckThatThisIsAValidPassword(membershipService);
   }
}

The blade and Turbine does everything for you, leaving you to just use it.  If I added MvcTurbine.FluentValidation to my project, simply having that validator somewhere in my project is all it takes to integrate it with an action that needs it, like this:

[HttpPost]
public ActionResult Index(LoginInputModel inputModel)
{
   if (ModelState.IsValid == false)
      return View("Index");
   membershipService.LogInAsUser(inputModel.Email, inputModel.Password);
   return RedirectToTheHomePage();
}

My validator will have run before the Index action was invoked, and ModelState will be loaded with any errors from the validator.  The validator even checked the email & password combination, keeping my controller clean.  Easy as pie.

The Bigger Picture

If you look at the code to this library, you’ll see a grand total of three classes.  There’s not much there.  I’m leveraging what Fluent Validation, MVC Turbine, ASP.NET MVC, and the many .Net IoC containers  already offer.  I think there is something special here, though, and it’s MVC Turbine’s role as the glue holding them all together.  By hooking into the ASP.NET MVC Pipeline at the appropriate places and abstracting away the registering and resolving of classes from the IoC container, it makes these types of integrations possible.  I’ve written a few of these integrations, and I can tell you — they all, pretty much, turn out like this.  You just get what you need into the right spots, and then you move on.

It deserves more discussion than I can give now, but that’s a more important point than this particular solution.  If you have integrations in MVC where you find yourself having to edit things in multiple places, or if you find yourself continually running to global.asax everytime you want to change something, you need to give MVC Turbine a look.

Download MvcTurbine.FluentValidation here.