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
public sealed class Student
{
public int Id { get; set; }
public int RollNo { get; set; }
public string FullName { get; set; }
public string EmailAddress { get; set; }
}
How to create the first validator?
For example, we have Student classes:
using FluentValidation;
internal sealed class StudentValidator : AbstractValidator<Student>
{
public StudentValidator()
{
RuleFor(x => x.FullName)
.NotEmpty()
.MinimumLength(5)
.MaximumLength(100);
RuleFor(x => x.Email)
.NotEmpty()
.EmailAddress(); // Built-in validation
}
}
Now we have to define a validator by inheriting AbstarctValidator class from FluentValidation.
using FluentValidation;
internal sealed class StudentValidator : AbstractValidator<Student>
{
public StudentValidator()
{
RuleFor(x => x.FullName)
.NotEmpty()
.MinimumLength(5)
.MaximumLength(100);
RuleFor(x => x.Email)
.NotEmpty()
.EmailAddress(); // Built-in validation
}
}
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
services.AddScoped<IValidator<Student>, StudentValidator>();
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 :
services
.AddValidatorsFromAssembly(typeof(DependencyInjection).Assembly);
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 :
services.AddValidatorsFromAssembly(
includeInternalTypes: true,
assembly: AssemblyReference.Assembly,
lifetime: ServiceLifetime.Transient
);
How to use the validator?
We can use validators by injecting the IValidator and specifying the name of the class like this :
public class StudentService : IStudentService
{
private readonly IValidator<Student> _validator;
public StudentService(IValidator<Student> validator)
{
_validator = validator;
}
public async Task Save(Student student)
{
var validationResult = await _validator.ValidateAsync(student);
// Add further logic to handle validationResult if needed
}
}
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