How to Use Fluent Validation in ASP.NET Core

Why we need validation?

Data validation is vital in development to maintain data integrity. By verifying information for accuracy (e.g., age not being 99999), we ensure our databases store only valid data, enhancing overall system reliability.

How to validate?

We can use data annotations for validations, write all custom code of validation or use some third party library which can do the job.

Using data annotations can make our code bloated, writing all custom validation stuff could be time taking, that is where Fluent Validation comes into party.

Introduction of Fluent Validation

FluentValidation is a .NET library (with 116M downloads) for building strongly-typed validation rules. It supports multiple platforms (.NET Standard 2.0, .NET Core 3.1, .NET 5,6,7)

How to use FluentValidation

  • Install following Nuget Package by using Nuget Package Manager or command
install-package FluentValidation.AspNetCore
  • Create your validator by inheriting from AbstracyValidator generic class and pass it your DTO/Request class

  • Add rules for your properties by using built in methods. How to Use Fluent Validation in ASP.NET Core

  • To use this validator first we need to tell our .NET API about it. Add following line in your Program.cs How to Use Fluent Validation in ASP.NET Core These two lines will search all validators in our assembly and register them, although we have few more ways as well to register it , you can read them here

  • To use our validator inject IValidator in constructor of desired class and we are good to go.

  • Call validate method and pass it your DTO and then by accessing its IsValid property we can verify if it was proper data or not. How to Use Fluent Validation in ASP.NET Core This was just basic overview of how to use this library in .NET Core, it comes with a variety of other features :

  • Localization

  • Define rules

  • Async validation

  • Apply set of rules

  • Set severity levels

  • Custom error codes

  • Validate specific properties

  • Built in and custom validators

You can read in detail about them at Official Docs I am big fan of their documentation , really simple and easy to understand.

GitHub Code of Demo

You can get code of Fluent Validation with implementation at this GitHub Repository

This article was originally published at https://mwaseemzakir.substack.com/ on .

Whenever you're ready, there are 3 ways I can help you:

  1. Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
  2. Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
  3. Patreon community : Get access to all of my blogs and articles at one place