LESSON 15 OF 22

15. Request Validation with FluentValidation

In this lesson, you will create FluentValidation validators for incoming API requests, separate field validation from workflow rules, and return consistent validation responses.

35 dk 102

Introduction

The fact that a Web API endpoint receives valid JSON does not mean that the data is valid or usable from a business perspective. A missing product name, negative price, invalid category identifier, or previously used stock code can cause unexpected failures later in the request pipeline.

In this lesson, we will validate request models with FluentValidation. FluentValidation keeps validation rules separate from DTO classes and helps us build a more readable, testable, and maintainable solution. We will also distinguish between two types of validation:

  • Field validation: Required values, lengths, formats, ranges, and basic data rules.
  • Workflow validation: Rules such as SKU uniqueness, resource existence, and whether an operation is valid for the current application state.

This separation prevents FluentValidation classes from becoming tightly coupled to databases and application workflows. Field validation is performed at the request boundary, while workflow validation remains the responsibility of the Application service.

Why use FluentValidation?

ASP.NET Core’s built-in model validation commonly relies on Data Annotations attributes. This can be sufficient for simple models, but DTOs can become crowded when validation rules grow more complex. FluentValidation defines these rules in separate validator classes.

The main benefits include:

  • Rules do not have to be stored inside the request model.
  • Rules are expressed through a readable fluent API.
  • Conditional rules, collection validation, and custom messages are straightforward.
  • Validators can be unit tested independently.
  • Validation failures can be grouped by property and returned to clients consistently.

The FluentValidation documentation describes manual validation as an explicit and controllable approach for ASP.NET Core applications, especially when asynchronous validation is required. We will use manual validation through the controller in this lesson.

Creating the request model

Let us define the request model for the product creation use case. This is not a Domain entity. It is an Application-layer DTO representing data received from the API client.

namespace Catalog.Application.Products.Create;

public sealed record CreateProductRequest(
    string Name,
    string Sku,
    decimal Price,
    int CategoryId,
    string? Description);

The request model contains only the fields required by this use case. Database keys, creation timestamps, and other system-generated values are not accepted from the client. As a result, the client cannot directly control every property of the Domain entity.

Adding the FluentValidation packages

In a current ASP.NET Core application, FluentValidation and FluentValidation.DependencyInjectionExtensions can be used to define and register validators. Select package versions compatible with the .NET version targeted by your solution.

dotnet add Catalog.Application package FluentValidation
dotnet add Catalog.API package FluentValidation.DependencyInjectionExtensions

Because the validator is defined in the Application layer, the FluentValidation reference should be added there first. The API project needs the dependency injection extension package to scan and register validators.

Writing field validation rules

Now create the CreateProductRequestValidator class. These rules depend only on the values inside the request. They do not query the database or inspect another service’s state.

using FluentValidation;

namespace Catalog.Application.Products.Create;

public sealed class CreateProductRequestValidator
    : AbstractValidator<CreateProductRequest>
{
    public CreateProductRequestValidator()
    {
        RuleFor(x => x.Name)
            .NotEmpty()
            .WithMessage("Product name is required.")
            .MaximumLength(120)
            .WithMessage("Product name cannot exceed 120 characters.");

        RuleFor(x => x.Sku)
            .NotEmpty()
            .WithMessage("SKU is required.")
            .Matches("^[A-Z0-9-]+$")
            .WithMessage("SKU may contain only uppercase letters, numbers, and hyphens.")
            .MaximumLength(40)
            .WithMessage("SKU cannot exceed 40 characters.");

        RuleFor(x => x.Price)
            .GreaterThan(0)
            .WithMessage("Price must be greater than zero.")
            .LessThanOrEqualTo(1_000_000)
            .WithMessage("Price cannot be greater than 1,000,000.");

        RuleFor(x => x.CategoryId)
            .GreaterThan(0)
            .WithMessage("A valid category must be selected.");

        RuleFor(x => x.Description)
            .MaximumLength(1000)
            .When(x => x.Description is not null)
            .WithMessage("Description cannot exceed 1,000 characters.");
    }
}

RuleFor starts a rule chain for a specific property. Methods such as NotEmpty, MaximumLength, GreaterThan, and Matches express common field rules. WithMessage controls the message returned to the client.

When several rules are defined for one property, FluentValidation evaluates them according to its cascade behavior. If you want to stop after the first failure, configure Cascade:

RuleFor(x => x.Sku)
    .Cascade(CascadeMode.Stop)
    .NotEmpty()
    .Matches("^[A-Z0-9-]+$");

In this example, the regular expression rule is not executed when the SKU is empty. This avoids sending redundant or confusing messages to the client.

Registering validators with dependency injection

In Program.cs, scan the Application assembly for validators:

using FluentValidation;
using Catalog.Application.Products.Create;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddControllers();
builder.Services.AddValidatorsFromAssemblyContaining<CreateProductRequestValidator>();

var app = builder.Build();

app.MapControllers();
app.Run();

This registration allows the container to resolve IValidator<CreateProductRequest> whenever it is requested. Validators are commonly registered as scoped or transient services. If you choose singleton registration, make sure that the validator does not depend on request-scoped services.

Manual validation inside the controller

Next, inject the validator into the controller and validate the request before calling the Application service. The following example assumes that the IProductService contract was defined in an earlier lesson.

using FluentValidation;
using Microsoft.AspNetCore.Mvc;
using Catalog.Application.Products.Create;

namespace Catalog.Api.Controllers;

[ApiController]
[Route("api/products")]
public sealed class ProductsController : ControllerBase
{
    private readonly IValidator<CreateProductRequest> _validator;
    private readonly IProductService _productService;

    public ProductsController(
        IValidator<CreateProductRequest> validator,
        IProductService productService)
    {
        _validator = validator;
        _productService = productService;
    }

    [HttpPost]
    [ProducesResponseType(StatusCodes.Status201Created)]
    [ProducesResponseType(StatusCodes.Status400BadRequest)]
    public async Task<IActionResult> Create(
        CreateProductRequest request,
        CancellationToken cancellationToken)
    {
        var validationResult = await _validator.ValidateAsync(
            request,
            cancellationToken);

        if (!validationResult.IsValid)
        {
            var errors = validationResult.Errors
                .GroupBy(error => error.PropertyName)
                .ToDictionary(
                    group => group.Key,
                    group => group.Select(error => error.ErrorMessage).ToArray());

            return ValidationProblem(errors);
        }

        var productId = await _productService.CreateAsync(
            request,
            cancellationToken);

        return CreatedAtAction(
            nameof(GetById),
            new { id = productId },
            new { id = productId });
    }

    [HttpGet("{id:int}")]
    public async Task<IActionResult> GetById(
        int id,
        CancellationToken cancellationToken)
    {
        var product = await _productService.GetByIdAsync(id, cancellationToken);
        return product is null ? NotFound() : Ok(product);
    }
}

ValidationProblem creates the problem details format used by ASP.NET Core for validation errors. The controller returns validation failures in one consistent structure, and the Application service is never called with a structurally invalid request.

A consistent validation response

When an invalid request is submitted, the client may receive a response similar to this:

{
  "type": "https://tools.ietf.org/html/rfc9110#section-15.5.1",
  "title": "One or more validation errors occurred.",
  "status": 400,
  "errors": {
    "Name": [
      "Product name is required."
    ],
    "Price": [
      "Price must be greater than zero."
    ]
  }
}

Because the errors property is a dictionary keyed by property name, frontend applications can display each message beside the corresponding input. Using the same response shape throughout the API simplifies client integration.

ASP.NET Core controller-based APIs can use [ApiController] behavior and ValidationProblemDetails to represent validation failures as standardized HTTP 400 responses. The grouping code above converts FluentValidation results into that familiar structure.

Separating field validation from workflow validation

A correctly formatted SKU is not necessarily unique. Checking uniqueness may require a repository or database query. Placing this rule inside a basic field validator mixes responsibilities and makes the validator dependent on persistence concerns.

For example, the Application service can perform the workflow checks:

public sealed class ProductService : IProductService
{
    private readonly IProductRepository _repository;
    private readonly IUnitOfWork _unitOfWork;

    public ProductService(
        IProductRepository repository,
        IUnitOfWork unitOfWork)
    {
        _repository = repository;
        _unitOfWork = unitOfWork;
    }

    public async Task<int> CreateAsync(
        CreateProductRequest request,
        CancellationToken cancellationToken)
    {
        if (await _repository.ExistsBySkuAsync(
                request.Sku,
                cancellationToken))
        {
            throw new BusinessRuleException(
                "Product.SkuAlreadyExists",
                "This SKU is already in use.");
        }

        if (!await _repository.CategoryExistsAsync(
                request.CategoryId,
                cancellationToken))
        {
            throw new BusinessRuleException(
                "Product.CategoryNotFound",
                "The selected category was not found.");
        }

        var product = Product.Create(
            request.Name,
            request.Sku,
            request.Price,
            request.CategoryId,
            request.Description);

        await _repository.AddAsync(product, cancellationToken);
        await _unitOfWork.SaveChangesAsync(cancellationToken);

        return product.Id;
    }
}

The distinction is now clear: FluentValidation answers “Is the request structurally valid?” while the Application service answers “Can this operation be performed in the current system state?” This makes validators easier to test and keeps the use case workflow visible.

Conditional and collection validation

Real-world requests often contain rules where one property depends on another. For example, a discount rate may be constrained only when a discount value is provided:

RuleFor(x => x.DiscountRate)
    .InclusiveBetween(0, 100)
    .When(x => x.DiscountRate.HasValue)
    .WithMessage("Discount rate must be between 0 and 100.");

For collections, use RuleForEach:

RuleForEach(x => x.Tags)
    .NotEmpty()
    .MaximumLength(40);

These rules still validate the structure of the incoming request. Whether a tag exists in the database or whether the current user is allowed to use it belongs in an Application service or policy.

Common mistakes

  • Using the entity as the request model: Keep API models and Domain entities separate so clients cannot modify fields they should not control.
  • Putting every check inside the validator: Do not fill one validator with uniqueness, authorization, and state checks. Separate field rules from workflow rules.
  • Running asynchronous rules through the wrong pipeline: Use ValidateAsync for database-backed checks. Asynchronous rules can cause problems when executed through a synchronous validation pipeline.
  • Returning exception messages directly: Do not expose technical exception details. Return safe messages and defined error codes for expected business failures.
  • Returning inconsistent property names: Ensure validation error keys follow the JSON naming policy used by your API.
  • Trusting only client-side validation: Client-side rules improve user experience, but server-side validation is always required for security and data integrity.

Short practice exercise

Apply the following exercise in your own project:

  1. Create a request model named CreateCategoryRequest.
  2. Add a required rule and an 80-character maximum for the category name.
  3. Allow only lowercase letters, numbers, and hyphens in the slug.
  4. Register the validator through assembly scanning.
  5. Call ValidateAsync in the controller and return errors with ValidationProblem.
  6. Check slug uniqueness inside the Application service.
  7. Send three requests through Swagger: an empty request, an invalid request, and a valid request. Compare the responses.

Conclusion

In this lesson, we created separate FluentValidation validators for request models. We defined basic field rules in the Application layer, registered validators with dependency injection, and executed them manually in the controller.

We also separated structural field validation from workflow validation that depends on the database or current system state. This distinction is important in Clean Architecture because request validity, use case feasibility, and Domain rules are different responsibilities.

In the next stage, we will handle validation failures and unexpected exceptions through centralized error handling so that API responses become even more consistent.

Sources