Model Validation Using FluentValidation in ASP.NET
Tags: dotnet, aspnet, validation, dotnetcore
Published: 2022-02-11 12:47:42


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.

![model validation in asp.net](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/fjl2lrkfx0mkx2x7wuyd.png)

> The Source code used in the article you can find in our [GitHub repository](https://github.com/Kylia669/fluentvalidation-example).

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. in this case, FluentValidation comes into play.
> FluentValidation is a library for building strongly-typed validation rules.

## Hands-On

Let’s start diving into the code:

```cs
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.

```cs
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.

```cs
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.

```cs
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. And if you liked this post, please give it a clap and share it with all of your friends.

Twitter: https://twitter.com/KyliaBoy
Linkedin: https://www.linkedin.com/in/andrew-kulta/

More articles you can find at:
https://blog.akyltech.com/