Why FluentValidation is the future for server-side validation in ASP.NET Core projects

Let’s start with the basics - what is FluentValidation? It’s a .NET and .NET Core library, which uses lambda expression to build validation rules for your models. It’s as geniusly simple as it sounds and can be downloaded from here.

In this blogpost the emphasis will be on whether or not you should use FluentValidation and what it can do for you as opposed to how to actually use it. I believe that if I dive into the technicalities of implementation and so forth, I will be pretty much rephrasing the awesome documentation, which you can find here.

The first thing that you might think of when hearing about FluentValidation is “why do I even need this when there’s a perfectly good annotation-based validation functionality out of the box?”.  This might be a valid point if your project is relatively small, doesn't require complex validation logic or you are not insistent on keeping your domain models as clean as possible (more of a personal preference to be honest, but still). Not to mention, that you can use FluentValidation in addition to the default built-in validation or any other ASP.NET Core validation provider.

Why should you use FluentValidation? What more does it have to offer?

  • Flexibility - FluentValidation offers you the ability to tackle complex validation logic very easily. With the option to use it along the built-in validation for simpler tasks. You wanna use it completely on its own? No problem, just disable the built-in validation with one line of code. It’s all up to you and that’s what makes it great.

services.AddMvc().AddFluentValidation(fv => {
 fv.RunDefaultMvcValidationAfterFluentValidationExecutes = false;
});
  • Ease of setup and use - again, just read through the ASP.NET Core documentation and you’ll see what I mean.

  • Highly testable - it comes with two extension methods (ShouldHaveValidationErrorFor and ShouldNotHaveValidationErrorFor), which makes testing feel like a cool summer breeze!

  • Decoupled rules and models - you can reuse your rules, while maintaining your models clean and free of validation logic and annotations. Whoa, it really is a win-win!

Drawbacks

The only drawback that I can think of is that FluentValidation is actually a server-side framework and doesn’t provide client-side validation directly as stated in the documentation. However, the provided metadata “can be applied to the generated HTML elements that can be used by a client-side framework such as jQuery Validate, in the same way that ASP.NET’s default validation attributes”.

For one of our next blog posts we may dive deeper and discuss Client-Side Validation with FluentValidation.