Must is a FluentValidation rule method that applies a predicate to custom validation logic. Chain it after RuleFor() and other requirements such as NotEmpty() or Length(). Validation succeeds when the predicate returns true. section 32.4.1 section 32.5
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
}
}
The currency validator combines basic checks with Must() to accept only GBP, USD, CAD, or EUR and attach a custom error message. section 32.4.1
Use Must() when validation depends on custom application rules:
- Validate a property against an allowed collection, such as supported currency codes. section 32.4.1
- Compare multiple values by accepting the containing model and the current property value, such as requiring CurrencyTo to differ from CurrencyFrom. section 32.4.1
- Extract repeated predicates into extension methods when several validators share the same rule. section 32.4.1
- Use injected services when a rule needs application data, such as currencies supplied by ICurrencyProvider. section 32.4.1
