Using FluentValidation for Model Validation in ASP.NET Core
This article explains how to integrate FluentValidation into ASP.NET Core for robust model validation, covering installation, defining validators, registering services, handling validation errors, conditional rules, cascade modes, asynchronous validation, and advanced features, with complete code examples.
ASP.NET Core provides built‑in model validation via attributes in System.ComponentModel.DataAnnotations , but its default validation is limited to controller actions and can be intrusive. FluentValidation offers a more powerful, non‑intrusive alternative that works in any scenario.
First, install the FluentValidation.AspNetCore NuGet package. Define the model to be validated, for example:
public class Student
{
public int Id { get; set; }
public int Age { get; set; }
public string Name { get; set; }
}Create a validator that inherits from AbstractValidator<Student> :
public class StudentValidator : AbstractValidator<Student>
{
public StudentValidator()
{
RuleFor(x => x.Age).InclusiveBetween(10, 50);
RuleFor(x => x.Name).NotEmpty().MaximumLength(5);
}
}Register the validator in Startup.ConfigureServices :
services.AddControllers()
.AddFluentValidation(conf =>
{
conf.RegisterValidatorsFromAssemblyContaining<StudentValidator>();
conf.RunDefaultMvcValidationAfterFluentValidationExecutes = false;
});In a controller, add an action that receives the model:
[HttpPost]
public IActionResult Add([FromBody] Student student)
{
return Ok(student);
}When validation fails, ASP.NET Core returns a 400 response with a JSON payload describing the errors. FluentValidation allows customizing these messages using placeholders, WithMessage , WithName , and conditional rules such as When , Unless , and ApplyConditionTo.CurrentValidator .
Advanced features include chaining multiple validators, setting CascadeMode to stop further checks after a failure, defining dependent rules, asynchronous validation with MustAsync , value transformation with Transform , failure callbacks via OnFailure , and overriding PreValidate for pre‑validation logic.
The article demonstrates both controller‑based and non‑controller scenarios, showing how to inject IValidator<Student> into services and invoke Validate or ValidateAsync manually.
Fulu Network R&D Team
Providing technical literature sharing for Fulu Holdings' tech elite, promoting its technologies through experience summaries, technology consolidation, and innovation sharing.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.