Fluent Validation in .NET

If you are interested to learn this topic via video then check out this video :

Fluent Validation is a powerful library used in the .NET world. It provides much flexibility over validation, with the ability to add custom validations and many built-in validators.

We can install Fluent Validation using the NuGet Package Manager console with the following command

Fluent Validation in .NET

How to create the first validator?

For example, we have Student classes:

Fluent Validation in .NET

Now we have to define a validator by inheriting AbstarctValidator class from FluentValidation.

Fluent Validation in .NET

I prefer to keep my validators sealed and internal

Registering Dependency of Validators

There are multiple ways to register dependencies of fluent validators.

  • Manual

  • Automatic

  • Manual Registration

    Fluent Validation in .NET

When the number of validators increases this approach becomes difficult, and then we can shift towards the second approach it will automatically search all validators and register their dependencies.

  • Automatic Registration

It will scan the complete assembly and register the validators :

Fluent Validation in .NET

By default, these will be registered as Scoped, but we can customize lifetime scope and either include internals or not in this process like this :

Fluent Validation in .NET

How to use the validator?

We can use validators by injecting the IValidator and specifying the name of the class like this :

Fluent Validation in .NET

ValidateAsync does the validation process and then by utilizing IsValid property we can figure out whether validation was successful or not.

We can call Validate or ValidateAsync as per need, in case of validation failure details can be found in the Errors property of the result.

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