Validating Values
This library provides extension methods for validating values using FluentValidation and encapsulating the result in a functional Result type. These methods allow you to easily perform synchronous or asynchronous validation of values, returning either the validated value or details about the validation failures.
Overview
These extensions enhance the usability of FluentValidation by integrating it with the Result<T, E> type from the Waystone.Monads library. Instead of throwing exceptions or dealing with error lists, you receive a clear result indicating success or failure, making error handling more straightforward and composable.
Methods
Validate
The Validate
extension method can be invoked on any value to synchronously validate the value using a provided AbstractValidator
.
record Hello(string value);
class HelloValidator : AbstractValidator<Hello>
{
public HelloValidator()
{
RuleFor(x => x.value).NotEmpty();
}
}
Hello hello = new("world!");
HelloValidator validator = new();
Result<Hello, ValidationErr> result = hello.Validate(validator);
If the validation succeeds, then an Ok
will be returned containing the original value. Otherwise, an Err
containing a ValidationErr will be returned.
ValidateAsync
The ValidateAsync
method can be invoked on any value to asynchronously validate the value using a provided AbstractValidator
.
Hello hello = new("world!");
HelloValidator validator = new();
CancellationTokenSource cts = new();
Result<Hello, ValidationErr> result = await hello.ValidateAsync(validator, cts.Token);
If the validation succeeds, then an Ok
will be returned containing the original value. Otherwise, an Err
containing a ValidationErr will be returned.
Last updated
Was this helpful?