FluentValidation¶
FluentValidation is a .NET library for building strongly-typed validation rules.
- FluentValidation 12 (currently in Preview) supports .NET 8 and newer.
- FluentValidation 11 supports .NET Standard 2.0, .NET Core 3.1, .NET 5 and newer.
If you’re moving from FluentValidation 11 to 12 please review the 12.0 Upgrade Guide
If you’re new to using FluentValidation, check out the Creating your first validator page.
Note
If you use FluentValidation in a commercial project, please sponsor the project financially. FluentValidation is developed for free by @JeremySkinner in his spare time and financial sponsorship helps keep the project going. Please sponsor the project via either GitHub sponsors or OpenCollective.
Example¶
public class CustomerValidator : AbstractValidator<Customer>
{
public CustomerValidator()
{
RuleFor(x => x.Surname).NotEmpty();
RuleFor(x => x.Forename).NotEmpty().WithMessage("Please specify a first name");
RuleFor(x => x.Discount).NotEqual(0).When(x => x.HasDiscount);
RuleFor(x => x.Address).Length(20, 250);
RuleFor(x => x.Postcode).Must(BeAValidPostcode).WithMessage("Please specify a valid postcode");
}
private bool BeAValidPostcode(string postcode)
{
// custom postcode validating logic goes here
}
}