Why use FluentValidation for validating models?
When it comes to Validating Models, aren’t we all leaning towards Data Annotations? The GO-TO Approach for Model validation in any .NET Application is Data Annotations, where you have to declare attributes over the property of models. Worked with it before?
Let's take an example of model Developer having multiple properties with data annotations applied to it,
- public class Developer {
- [Required]
- public string FirstName {
- get;
- set;
- }
- [Required]
- public string LastName {
- get;
- set;
- }
- [EmailAddress]
- public string Email {
- get;
- set;
- }
- [PhoneNumber][Range(maximum: 10)]
- public int MobileNumber {
- get;
- set;
- }
- }
It is fine for beginners. But once you start learning clean code, or begin to understand the SOLID principles of application design, you would just never be happy with Data Annotations as you were before.
It is clearly not a good approach to combine your models and validation logic. With the implementation of Data Annotations in .NET Classes, the problem is that there will be a lot of duplicate lines of code throughout your application.
What if the Developer Model class is to use in another application/method where these Attribute validation changes?
What if you need to validate a model that you don’t have access to?
There are quite a lot of serious issues with this approach for a scalable system. Unit testing can get messy as well. You will definitely end up building multiple model classes which will no longer be maintainable in the long run.
So, what’s the solution?
There is a library, Fluent Validations, that can turn up the validation game to a whole new level, giving you total control.