FluentValidation in ASP.NET Core

FluentValidation

FluentValidation is a way to define strongly typed validation for classes in the form of a Fluent API. The term fluent in this case refers to a code structure where a function always return the modified object. This way, you can chain together multiple method calls and produce very readable source code, especially in configurations where it is often used. You may already be familiar with this structure from areas like the ASP.NET setup or LINQ.

Installation & Setup

To use FluentValidation, you first need to install corresponding NuGet package FluentValidation.AspNetCore. After that, the only thing left to do is the configuration in your applications startup class. Just add a call to AddFluentValidation in the method ConfigureServices and you’re all set! To work correctly with the DI infrastructure, the validators must be defined here afterwards tough:

Pitfalls

There are a few things to be considered when using the library. For example, the regular asp.net validation using DataAttributes is still active and will be applied after the fluentvalidation. It may be helpful to clean up old code to avoid unexpected side effects.

TL;DR

In my opinion, FluentValidation offers a very nice way to define strongly typed validation rules in ASP.NET (Core), without having to mess up your classes. However, there are many more details I haven’t covered yet. As I mentioned earlier, the documentation of the project is a very good place to get answers to potential questions and general information, but you also might find posts on various details here in the future.

Software Developer (C#, Java / Desktop, Web, Mobile, Games (VR)), Triathlete & Coach - mjurtz.com — Sign up to my newsletter: coding.mjurtz.com

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store