DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Reduce Frontend Complexity in ASP.NET Razor Pages Using HTMX
  • GDPR Compliance With .NET: Securing Data the Right Way
  • How to Enhance the Performance of .NET Core Applications for Large Responses
  • Zero to AI Hero, Part 3: Unleashing the Power of Agents in Semantic Kernel

Trending

  • Chaos Engineering and Kafka In Action: Topic Level Idempotence and Retry Check
  • Building a Feature Store With Neo4j and Feast
  • The Missing `bandit` for AI Agents: How I Built a Static Analyzer for Prompt Injection
  • Data Integration Landscape 2026: Event Streaming, API, and Batch in the Era of Agentic AI

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Coding
  3. Frameworks
  4. Model Validation Using FluentValidation in ASP.NET

Model Validation Using FluentValidation in ASP.NET

One requirement for any good API is the ability to validate input relying on different business rules. In this post, we'll look at model validation in ASP.NET

By 
Andrew Kulta
·
Feb. 21, 22 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
8.1K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

The source code used in the article can be found in our GitHub repository.

One of the requirements for a good API is the ability to validate input relying on different business rules. As developers, we always care about validation when getting any data from clients.

ASP.NET has a built-in mechanism to validate input payloads on the API level. But it’s limited when we are trying to validate input payload with custom business rules. We can move validation inside our business layer and apply our custom validation for input models. Choosing this decision, we are making controllers thin. It just makes a proper model binding and invokes the required service method. Functional tests could cover such behavior, and we don’t need to write unit tests for such thin controller actions.

We can write our custom validation rules, invent a new validation tool and come to a not so handy code with many ifs and in this case, FluentValidation comes into play.

FluentValidation is a library for building strongly-typed validation rules.

Let’s start diving into the code:

C#
 
public class ApiController : BaseController
{
    private readonly IService _service;
    
    public TimeEntryController(IService service)
    {
        _service = service;
    }


    [ProducesResponseType(typeof(Response), StatusCodes.Status201Created)]
    [ProducesResponseType(typeof(ExceptionModel), StatusCodes.Status400BadRequest)]
    [HttpPost]
    public async Task<ObjectResult> CreateAsync([FromBody] CreateRequest request)
    {
        var response = await this._service.CreateAsync(request);
        return this.Ok(response);
    }
}


The controller becomes clean and straightforward. ASP.NET still applies validation for model fields, but business validation happens in the service layer.

C#
 
public class Service
{
    private readonly IValidationService _validationService;
    
    public TimeEntryService(IValidationService validationService)
    {
        _validationService = validationService;
    }

    public async Task<Response> CreateAsync(CreateRequest request)
    {
        this._validationService.EnsureValid(request);
        // Implementation
        return new Response();
    }

}


The first thing we want to do before starting the implementation for business logic is to apply our validation to the input payload. Each payload requires a proper validator, and it causes a situation when we need to inject many validators into our service to validate input models. It’s better to avoid such cases and introduce another service responsible for model validation only, and it hides all complexity of business validation from other services.

C#
 
public class ValidationService
{
    private readonly IDictionary<Type, Type> _validators;
    private readonly IServiceProvider _serviceProvider;

    public ValidationService(IServiceProvider serviceProvider)
    {
        this._serviceProvider = serviceProvider;
        this._validators = new Dictionary<Type, Type>
        {
            { typeof(CreateRequest), typeof(CreateRequestValidator) },
        };
    }

    private AbstractValidator<T> GetValidator<T>()
    {
        var modelType = typeof(T);
        var hasValidator = this._validators.ContainsKey(modelType);
        if (hasValidator == false)
        {
            throw new Exception("Missing validator");
        }

        var validatorType = this._validators[modelType];
        var validator = _serviceProvider.GetService(validatorType) as AbstractValidator<T>;
        return validator;
    }

    public void EnsureValid<T>(T model)
    {
        var validator = this.GetValidator<T>();
        var result = validator.Validate(model);
        if (result.IsValid == false)
        {
            throw new Exception(result.ToString());
        }
    }
}


We have a proper structure for validation and are ready to add model validators. FluentValidation gives us a base class AbstractValidator<T> to inherit for our custom validators.

C#
 
public class CreateRequestValidator : AbstractValidator<CreateRequest>
{
    public CreateRequestValidator()
    {
        RuleFor(r => r.Name).Required();
        RuleFor(r => r.Date.ToUniversalTime()).LessThan(DateTime.UtcNow);
    }
}


Conclusion

We got a clean way to separate validation for input requests into small classes. We can write complex validators that rely on business rules, and it’s simple for us to test validators as a small independent part of the solution.

Any questions or comments? Ping me on LinkedIn or comment below.

ASP.NET

Published at DZone with permission of Andrew Kulta. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Reduce Frontend Complexity in ASP.NET Razor Pages Using HTMX
  • GDPR Compliance With .NET: Securing Data the Right Way
  • How to Enhance the Performance of .NET Core Applications for Large Responses
  • Zero to AI Hero, Part 3: Unleashing the Power of Agents in Semantic Kernel

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook