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.
public class StudentValidator : AbstractValidator<StudentDto>
{
public StudentValidator()
{
RuleFor(x => x.Email).EmailAddress();
RuleFor(x => x.PhoneNumber).Length(11);
RuleFor(x => x.Age).GreaterThanOrEqualTo(18);
}
}
- To use this validator first we need to tell our .NET API about it. Add following line in your Program.cs
using FluentValidation;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
var assembly = typeof(Program).Assembly;
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddValidatorsFromAssembly(assembly);
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.
private readonly IValidator<StudentDto> _validator;
private static List<StudentDto> students = new();
public StudentController(IValidator<StudentDto> validator)
{
_validator = validator;
}
[HttpPost]
public string Add(StudentDto student)
{
var validate = _validator.Validate(student);
if (validate.IsValid)
{
students.Add(student);
return "Student added successfully";
}
return string.Join(", ", validate.Errors.Select(e => e.ErrorMessage));
}
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
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