ASP.NET Core  

How to Implement FluentValidation in ASP.NET Core with Example

Introduction

When building ASP.NET Core Web API applications, validating user input is one of the most important steps. Without proper validation, your application can accept incorrect data, which can lead to bugs, security issues, and poor user experience.

By default, ASP.NET Core provides basic validation using Data Annotations. However, as your application grows, this approach can become messy and hard to maintain.

This is where FluentValidation comes into the picture.

In simple words, FluentValidation is a powerful and flexible validation library that allows you to write clean, readable, and maintainable validation rules.

In this step-by-step guide, you will learn how to implement FluentValidation in ASP.NET Core with real examples, simple explanations, and practical use cases.

What is FluentValidation?

FluentValidation is a popular .NET library used for building strongly-typed validation rules using a fluent interface.

Instead of adding validation attributes inside your model, you define validation logic in separate classes.

This makes your code:

  • Cleaner

  • Easier to read

  • Easier to test

  • More maintainable

Real-life example:

Think of a form validation system.

Without FluentValidation:

  • Rules are scattered in models

With FluentValidation:

  • Rules are organized in a dedicated validator class

Why Use FluentValidation in ASP.NET Core?

Using FluentValidation provides several benefits:

  • Clean separation of concerns

  • Better readability of validation rules

  • Easy to maintain and update

  • Supports complex validation scenarios

In real-world applications, especially enterprise systems, FluentValidation is widely used to handle complex validation logic.

Step 1: Create ASP.NET Core Web API Project

dotnet new webapi -n FluentValidationDemo
cd FluentValidationDemo

Step 2: Install FluentValidation Package

dotnet add package FluentValidation.AspNetCore

This package integrates FluentValidation with ASP.NET Core.

Step 3: Register FluentValidation in Program.cs

using FluentValidation;
using FluentValidation.AspNetCore;

builder.Services.AddControllers()
    .AddFluentValidation(config =>
    {
        config.RegisterValidatorsFromAssemblyContaining<Program>();
    });

This automatically registers all validators in your project.

Step 4: Create a Model

public class Product
{
    public string Name { get; set; }
    public decimal Price { get; set; }
    public string Email { get; set; }
}

This is a simple model where we will apply validation.

Step 5: Create a Validator Class

using FluentValidation;

public class ProductValidator : AbstractValidator<Product>
{
    public ProductValidator()
    {
        RuleFor(x => x.Name)
            .NotEmpty().WithMessage("Name is required")
            .MinimumLength(3).WithMessage("Name must be at least 3 characters");

        RuleFor(x => x.Price)
            .GreaterThan(0).WithMessage("Price must be greater than 0");

        RuleFor(x => x.Email)
            .NotEmpty().WithMessage("Email is required")
            .EmailAddress().WithMessage("Invalid email format");
    }
}

Explanation:

  • RuleFor defines validation rules

  • You can chain multiple conditions

  • Custom messages improve user experience

Step 6: Use Validation in Controller

[ApiController]
[Route("api/[controller]")]
public class ProductController : ControllerBase
{
    [HttpPost]
    public IActionResult Create(Product product)
    {
        return Ok("Product is valid");
    }
}

ASP.NET Core automatically triggers FluentValidation before the controller executes.

If validation fails:

  • Request is rejected

  • Error messages are returned

Step 7: Sample Request and Response

Invalid Request:

{
  "name": "",
  "price": 0,
  "email": "invalid"
}

Response:

{
  "errors": {
    "Name": ["Name is required"],
    "Price": ["Price must be greater than 0"],
    "Email": ["Invalid email format"]
  }
}

Step 8: Advanced Validation Example

RuleFor(x => x.Name)
    .Must(name => name != "admin")
    .WithMessage("Name cannot be admin");

You can write custom logic easily.

Step 9: Real-World Use Case

In an e-commerce application:

  • Validate product data before saving

  • Ensure price is valid

  • Validate user email during registration

This ensures data consistency and prevents invalid data entry.

Common Mistakes to Avoid

  • Not registering validators

  • Mixing validation logic inside models

  • Writing overly complex rules in one place

Advantages of FluentValidation

  • Clean and readable code

  • Centralized validation logic

  • Easy to test

  • Supports complex scenarios

Disadvantages of FluentValidation

  • Extra setup required

  • Learning curve for beginners

When Should You Use FluentValidation?

Use it when:

  • Application has complex validation rules

  • You want clean architecture

  • You want maintainable code

Avoid when:

  • Project is very small

  • Only simple validation is needed

Summary

FluentValidation in ASP.NET Core is a powerful way to handle input validation in a clean and structured manner. By separating validation logic from models and using a fluent API, developers can create readable, maintainable, and scalable applications. With proper implementation, FluentValidation improves code quality, enhances user experience, and ensures that only valid data enters your system.