Introduction
The FluentValidation library provides the functionality developers need to validate data before committing it to a data source like a database. However, what this library provides out of the box doesn't meet every developer's needs, so you can extend the base validations. Learn how to create extension methods for FluentValidation.
🔷 FluentValidation works with project types ranging from console to web.
Custom Validator
IRuleBuilderOptions interface: One of the most useful reasons to work directly with IRuleBuilderOptions is to create reusable validation methods. The important distinction is that IRuleBuilderOptions represents a rule builder that already has a validator attached, making it possible to configure that validator.
For demonstration, the following language extension validates a DateOnly class property. Here, a date range is hard-coded, which means that if a business rule changes, the code needs to be recompiled, which will be addressed in version 2 of the BirthDateRule extension.
Version 1
public static class RuleBuilderExtensions
{
/// <summary>
/// Defines a validation rule for a birthdate, ensuring the year is within a valid range.
/// </summary>
/// <typeparam name="T">The type of the object being validated.</typeparam>
/// <param name="ruleBuilder">
/// The <see cref="IRuleBuilder{T, TProperty}"/> used to build the validation rule.
/// </param>
/// <returns>
/// An <see cref="IRuleBuilderOptions{T, TProperty}"/> that represents the configured validation rule.
/// </returns>
/// <remarks>
/// The birthdate year must be greater than the year calculated as 120 years before the current year
/// and less than or equal to the current year.
/// </remarks>
public static IRuleBuilderOptions<T, DateOnly> BirthDateRule<T>(this IRuleBuilder<T, DateOnly> ruleBuilder)
{
int minYear = DateTime.Now.AddYears(-120).Year;
return ruleBuilder
.Must(x => x.Year > minYear && x.Year <= DateTime.Now.Year)
.WithMessage("'{PropertyName}'" +
$" must be greater than {minYear} " +
$"year and less than or equal to {DateTime.Now.Year} ");
}
}
Sample use
Model
public class Person : IPerson
{
public required string FirstName { get; set; }
public required string LastName { get; set; }
public DateOnly BirthDate { get; set; }
}
Mocked data with two Person's with invalid BirthDate.
internal class MockedData
{
public static List<Person> PeopleList() =>
[
new Person
{
FirstName = "John",
LastName = "Doe",
BirthDate = new DateOnly(1985, 3, 15)
},
new Person
{
FirstName = "Jane",
LastName = "Smith",
BirthDate = new DateOnly(1990, 7, 22)
},
new Person
{
FirstName = "Michael",
LastName = "Johnson",
BirthDate = new DateOnly(1878, 11, 5)
},
new Person
{
FirstName = "David",
LastName = "Brown",
BirthDate = new DateOnly(1924, 9, 30)
}
];
}
Validate mocked data
var people = MockedData.PeopleList();
var validator = new PersonValidator();
foreach (var (index, person) in people.Index())
{
var result = validator.Validate(person);
if (!result.IsValid)
{
SpectreConsoleHelpers.PrintValidationErrors(index, result.Errors);
}
else
{
SpectreConsoleHelpers.PrintValidPerson(index, person);
}
}
Version 2
- JsonRoot() is defined in NuGet package ConsoleConfigurationLibrary
This version reads the minimum date from appsettings.json.
public static class RuleBuilderExtensions
{
/// <param name="ruleBuilder">
/// The <see cref="IRuleBuilder{T, TProperty}"/> to which the validation rule is applied.
/// </param>
/// <typeparam name="T">The type of the object being validated.</typeparam>
extension<T>(IRuleBuilder<T, DateOnly> ruleBuilder)
{
/// <summary>
/// Adds a validation rule to ensure that a <see cref="DateOnly"/> value representing a birthdate
/// falls within a valid range of years.
/// </summary>
/// <returns>
/// An <see cref="IRuleBuilderOptions{T, TProperty}"/> that allows further configuration of the validation rule.
/// </returns>
/// <remarks>
/// The valid range for the birthdate is determined dynamically based on the current year and
/// a minimum year offset specified in the application's configuration.
/// </remarks>
/// <exception cref="ArgumentNullException">
/// Thrown if the configuration section for <see cref="DateOnlyConfiguration"/> is not found or is null.
/// </exception>
public IRuleBuilderOptions<T, DateOnly> BirthDateRule()
{
var section = JsonRoot().GetSection(nameof(DateOnlyConfiguration));
var minYear = DateTime.Now.AddYears(section.Get<DateOnlyConfiguration>()!.MinYear).Year;
return ruleBuilder
.Must(x => x.Year > minYear && x.Year <= DateTime.Now.Year)
.WithMessage($"Birth date must be greater than {minYear} " +
$"year and less than or equal to {DateTime.Now.Year} ");
}
}
}
appsettings.json
{
"DateOnlyConfiguration": {
"MinYear": -100
}
}
Summary
An example of IRuleBuilder and IRuleBuilderOptions has been shown for extending a FluentValidation validator which can be used to create your own extensions.

Top comments (0)