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 2 ways I can help you:
Promote yourself to 10000+ subscribers by sponsoring this newsletter
Patreon Community: Join and gain access to the 200+ articles I have published so far in one place. Join here
So simple and straightforward
Awesome stuff Muhammad friend, I am a big fan of fluent syntax, it makes the code more readable!