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
How to create the first validator?
For example, we have Student classes:
Now we have to define a validator by inheriting AbstarctValidator class from FluentValidation.
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
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 :
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 :
How to use the validator?
We can use validators by injecting the IValidator and specifying the name of the class like this :
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.
Whenever you're ready, there are 3 ways I can help you:
- Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
- Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
- Patreon community : Get access to all of my blogs and articles at one place