Lesson 4 of 8
FluentValidation - Business Rule Validation
FluentValidation provides expressive, testable validation rules with clean syntax. Unlike Data Annotations on request models, FluentValidation separates validation logic from DTOs, supports async database checks (e.g., does this email already exist?), and composes complex rules cleanly.
FluentValidation Rules & Async Validators
using FluentValidation;
// dotnet add package FluentValidation.AspNetCore
// ━━ Validator class ━━
public class CreateProductRequestValidator : AbstractValidator<CreateProductRequest>
{
public CreateProductRequestValidator(IProductRepository repository)
{
// ━━ Name rules ━━
RuleFor(x => x.Name)
.NotEmpty().WithMessage("Product name is required")
.Length(3, 200).WithMessage("Name must be between 3 and 200 characters")
.Matches(@"^[a-zA-Z0-9s-'.]+$").WithMessage("Name contains invalid characters")
.MustAsync(async (name, ct) => !await repository.SlugExistsAsync(SlugOf(name), ct: ct))
.WithMessage("A product with this name already exists");
// ━━ Price rules ━━
RuleFor(x => x.Price)
.GreaterThan(0).WithMessage("Price must be greater than zero")
.LessThanOrEqualTo(999_999.99m).WithMessage("Price exceeds maximum allowed")
.PrecisionScale(18, 2, false).WithMessage("Price can have at most 2 decimal places");
// ━━ Category ━━
RuleFor(x => x.CategoryId)
.NotEmpty().WithMessage("Category is required")
.MustAsync(async (id, ct) => await repository.ExistsByIdAsync(id, ct))
.WithMessage("Category does not exist");
// ━━ Stock ━━
RuleFor(x => x.InitialStock)
.GreaterThanOrEqualTo(0).WithMessage("Stock cannot be negative")
.LessThanOrEqualTo(100_000).WithMessage("Stock too high");
// ━━ Conditional rules ━━
When(x => x.Description is not null, () =>
{
RuleFor(x => x.Description!)
.MaximumLength(4000)
.Must(desc => !desc.Contains("<script"))
.WithMessage("Description contains invalid HTML");
});
}
private static string SlugOf(string name) =>
name.ToLower().Replace(" ", "-").Trim();
}
// ━━ Registration ━━
// dotnet add package FluentValidation.AspNetCore
builder.Services.AddValidatorsFromAssembly(typeof(CreateProductRequestValidator).Assembly);
// ━━ Integration with [ApiController] - auto-validate ━━
builder.Services
.AddFluentValidationAutoValidation()
.AddFluentValidationClientsideAdapters();
// Now [ApiController] calls FluentValidation automatically - 400 on invalid input
// ━━ Manual validation in service ━━
public class ProductService2(IValidator<CreateProductRequest> validator)
{
public async Task<Result<ProductResponse>> CreateAsync(CreateProductRequest request, CancellationToken ct)
{
var validation = await validator.ValidateAsync(request, ct);
if (!validation.IsValid)
{
var errors = validation.Errors.Select(e => e.ErrorMessage).ToArray();
return Result<ProductResponse>.Validation(string.Join("; ", errors));
}
return Result<ProductResponse>.Success(new ProductResponse(Guid.NewGuid(), request.Name, "", request.Price, "USD", "", request.InitialStock, request.InitialStock > 0, DateTime.UtcNow));
}
}
// Placeholder types
record Result<T>(bool IsSuccess, T? Value = default, string? Error = null)
{
public static Result<T> Success(T v) => new(true, v);
public static Result<T> Validation(string e) => new(false, Error: e);
}
interface IValidator<T> { Task<ValidationResult> ValidateAsync(T v, CancellationToken ct); }
class ValidationResult { public bool IsValid { get; set; } public System.Collections.Generic.List<ValidationFailure> Errors { get; set; } = []; }
class ValidationFailure { public string ErrorMessage { get; set; } = ""; }
interface IProductRepository { Task<bool> SlugExistsAsync(string slug, Guid? exclude = null, CancellationToken ct = default); Task<bool> ExistsByIdAsync(Guid id, CancellationToken ct); }Tip
Tip
Practice FluentValidation Business Rule Validation in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
.NET provides a unified platform for building various application types
Practice Task
Note
Practice Task - (1) Write a working example of FluentValidation Business Rule Validation from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Quick Quiz
Common Mistake
Warning
A common mistake with FluentValidation Business Rule Validation is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready dotnet code.
Finished this lesson?