Why use fluentvalidation instead of ASP.NET MVC validation

DavidS picture DavidS · Jun 7, 2011 · Viewed 10.1k times · Source

In which circumstances would you choose FluentValidation (FV) over the ASP.NET MVC 3 way?

What are the advantages of FV over MVC? I realise that with the latter we have to write much more code and can litter the code with Data Annotations. Moreover, it would seem to be easier to write custom validation using FV than MVC. However, with MVC it is possible to make use the data annotation and plug jQuery validation in.

So what in your view would make you choose one over the other? Are there circumstances where you would even use both?

Answer

Steve Wilkes picture Steve Wilkes · Jun 7, 2011

Fluent validation is one way of setting up dedicated validator objects, which you would use when you want to treat validation logic as separate from business logic. The aspect-oriented programming (AOP) paradigm enables separation of cross-cutting concerns within a system, and validation is one such concern. Separating validation helps clean up your domain code and make it more cohesive, as well as giving you a single place to look for validation logic.

MVC annotation-driven validation is a very 'cheap' way to get some basic validation into an application, without going to the hassle of creating dedicated validator objects, creating a validation system which organizes them and plugging it all together. It's very easy to set up, but can make your domain objects less clean.

For small systems where all the validation logic can be handled using annotations, I would recommend just using annotations, because they're so easy to set up. For larger, more complex systems, I would recommend separating the validation concern using validator objects.

I personally like to use both approaches: add validation attributes to ViewModel classes (which means the annotations don't clutter up my domain objects), as well as having dedicated validator objects within my domain layer. This is a small amount of duplication, but using annotations is so quick and easy, I find it worth the extra maintenance cost.