FluentValidation in .Net Core 3.1
Fluent validation is one of the cool things I came across recently in .Net Core. So, thought about creating a blog post about it. And here it goes:
Fluent validation helps you to create validation rules for the models. Instead of hardcoding the rules on the model using DataAnnotations, Fluent validation gives you an elegant approach to write validation rules. In simple terms, it separates the cumbersome validation rules from the models, and write it in a separate class, so that we can keep the models just as a class containing a bunch of properties. Let’s see how can incorporate the fluent validation in our application.
Here I have a created a sample WebAPI project using ASP.Net Core 3.1, and the project structure is as follows:
Before we go to the demo, this is the guy who created the FluentValidator package. His name is Jeremy Skinner.
The steps I followed are:
1. Took the FluentValidation package fromNuGet and installed in my project:
Install-Package FluentValidation.AspNetCore -Version 9.5.0
2. Made necessary code changes to StartUp.cs to incorporate fluentvalidation in the solution.
3. Before we continue, my Customer model class is as shown below:
4. For creating validation rules, first we need to create a new validator class. Here I have created CustomerValidator class and inherited it from AbstractValidator<T> base class, passing the type in the place of T (Here Customer).
Then created some rules for the model. The rules are written inside the constructor of the new class. I have written rules for the Id, Age, Email, Age as well as the Product class’s properties. I think the rules are self explanatory.
5. We don’t need to add anything in the Customer controller. That's the beauty of fluentValidation package!
Cool. The set up is complete. Now let’s see the results in action:
From my postman I have issued a POST request with the Name field’s length exceeding the character length 10, as we previously set in the fluent validation rule. And you can see the response as below:
And if I issue a request adhering to my validation rule, it will return the 200 ok result.
As another use case, I have added the age as 90 and issues a POST request. And you can see the result:
Conclusion:
Okay. That was it. Try using the fluent validation in your application, and let me know the response. Also I plan to write a part 2 of fluentValidation going in more scenarios.
Thanks for reading!