Fluent Validation And Its Advantages

What is Fluent Validation?

 
Fluent Validation is a validation library for .NET, used for building strongly typed validation rules for business objects.
 
Fluent validation is one way of setting up dedicated validator objects, that you would use when you want to treat validation logic as separate from business logic.
  • Fluent validations use Fluent interface and lambda expressions to build validation rules.
  • Fluent validation is a free-to-use .NET validation library that helps you make your validations clean and easy to both create and maintain.
  • It even works on external models that you don’t have access to, with ease. 

Advantages of using Fluent Validations

  • Speed of development- It is easy to work with.
  • Decoupling validation rules and models- Fluent Validation allows you to separate validation rules from your model and helps you structure the rules so that they are nice and readable.
  • Speed of execution- The rules are immutable objects meaning you can create them once and cache them. When the rules are part of the model, you’re needlessly setting them up every time. This is not a problem when working with one simple entity, but quickly becomes a performance problem when you’re working with multiple complex validators over thousands of rows. Benchmarking showed that we saved considerable time doing this – one import went from a huge amount of time to comparatively very less when we started caching validators.
  • Ability to work with odd relationships and dependent entities. Many of the entities we work with have dependencies on other things in the system, even though they’re not ‘formally’ related. With fluent validation, we could write validators that handle this easily.
  • Efficient unit testing- Validation rules are super easy to test. 
For small systems, I would recommend just using Data Annotations, because they’re so easy to set up. For larger, more complex systems, I would recommend separating the validation concern using validator objects with Fluent Validation.