FluentValidation.AspNetCore connects FluentValidation to ASP.NET Core MVC and Razor Pages validation. Install the NuGet package, call AddFluentValidationAutoValidation() in Program.cs, and register validators with dependency injection. section 32.4.2 section 32.5
A typical configuration can:
- Discover validators automatically with AddValidatorsFromAssemblyContaining<Program>(), or register individual validators manually. section 32.4.2 section 32.5
- Disable DataAnnotations validation to avoid running two validation systems, unless both are temporarily needed during migration. section 32.4.2 section 32.5
- Keep validators near the models they validate; Razor Pages input-model validators can be nested inside the PageModel. section 32.4.2
Listing 32.15 Configuring FluentValidation in an ASP.NET Core application
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
builder.Services.AddValidatorsFromAssemblyContaining<Program>(); #1
builder.Services.AddFluentValidationAutoValidation( #2
x => x.DisableDataAnnotationsValidation = true) #2
.AddFluentValidationClientsideAdapters(); #3
ValidatorOptions.Global.LanguageManager.Enabled = false; #4
A complete Program.cs configuration scans the assembly for validators, enables automatic validation, disables DataAnnotations, adds client-side adapters, and disables localized language management. section 32.4.2
