Fluent Validation is a validation library available as a NuGet package, that can be easily implemented by developers. It uses a fluent API that leverages lambda expressions to validate rules.
In this example we use FluentValidation.AspNetCore, but in Libraries FluentValidation is also an option.
Sample
The solution has a POST endpoint that allows users to submit a Product.
The Fluent Validation is executed on the request, and in case it fails, it returns a BadRequest.
usingFluentValidation.AspNetCore;varbuilder=WebApplication.CreateBuilder(args);// Add services to the container.
builder.Services.AddControllers();// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();builder.Services.AddSwaggerGen();builder.Services.AddFluentValidation(conf=>{conf.RegisterValidatorsFromAssembly(typeof(Program).Assembly);conf.AutomaticValidationEnabled=false;});varapp=builder.Build();// Configure the HTTP request pipeline.
if(app.Environment.IsDevelopment()){app.UseSwagger();app.UseSwaggerUI();}app.UseAuthorization();app.MapControllers();app.Run();
As the package is added, the AddFluentValidation extension is added to the Service Collection. It is necessary to register the validators using RegisterValidatorsFromAssembly.
The AutomaticValidationEnabled was set to false, so we can control the validation when debugging the solution. If you don’t do that, ASP.NET validation occurs automatically by default, at the time of model binding.
publicclassProductViewModelValidator:AbstractValidator<ProductViewModel>{publicProductViewModelValidator(){RuleFor(model=>model.Name).NotNull().NotEmpty().WithMessage("Please specify a name");RuleFor(model=>model.Sku).NotNull().NotEmpty().Length(3,10);RuleFor(model=>model.Quantity).GreaterThanOrEqualTo(0);RuleFor(model=>model.Price).NotEqual(0).When(model=>model.Quantity>0).WithMessage("Please specify a price");}}
In here some validations were added to the ProductViewModel. We check whether the properties are not null, not empty, we specify error messages, having the minimal length of 3 and max length of 10, value is greater than or equal to zero, and also a property validation based on property value.
Looking at the controller, the validation happens within the POST method:
Join the conversation! Share your thoughts and connect with other readers.