FluentValidation is a .NET validation library for ASP.NET Core MVC and Razor Pages. It replaces attribute-based DataAnnotations rules with strongly typed validators, keeping binding models focused on data and validation rules in separate classes. section 32.0 section 32.4
A typical FluentValidation integration follows these steps:
- Install the FluentValidation.AspNetCore NuGet package. section 32.4.2
- Create a validator deriving from AbstractValidator<T> and add chained rules with RuleFor(). section 32.4.1
- Register validators with dependency injection, manually or through assembly scanning. section 32.4.2
- Call AddFluentValidationAutoValidation() and disable DataAnnotations validation when FluentValidation should be the sole system. section 32.4.2
Currency converter validator
A CurrencyConverterModel can remain free of validation attributes while its validator chains requirements such as NotEmpty(), Length(3), and MustBeCurrencyCode(). Must() supports cross-property rules, such as rejecting a CurrencyTo value equal to CurrencyFrom. Reusable rules can be extracted into extension methods, and validators can receive injected services such as an ICurrencyProvider. section 32.4.1 section 32.4.1
Listing 32.11 A FluentValidation validator for the currency converter binding model
public class CurrencyConverterModelValidator #1
: AbstractValidator<CurrencyConverterModel> #1
{
private readonly string[] _allowedValues #2
= new []{ "GBP", "USD", "CAD", "EUR" }; #2
public CurrencyConverterModelValidator() #3
{
RuleFor(x => x.CurrencyFrom) #4
.NotEmpty() #5
.Length(3) #5
.Must(value => _allowedValues.Contains(value)) #6
.WithMessage("Not a valid currency code"); #6
RuleFor(x => x.CurrencyTo)
.NotEmpty()
.Length(3)
.Must(value => _allowedValues.Contains(value))
.WithMessage("Not a valid currency code");
RuleFor(x => x.Quantity)
.NotNull()
.InclusiveBetween(1, 1000); #7
}
}
Inspect a complete validator showing AbstractValidator<T>, RuleFor(), chained requirements, allowed currency codes, and custom messages. section 32.4.1
