FluentValidation in ASP.NET Core

FluentValidation is a wonderful validation package that is around for years. Last week I was busy with a new application in ASP.NET core. I wanted to add some validation and didn’t used FluentValidation in ASP.NET Core before. So I wanted to see if things where changed. This blog post contains some examples from the official FluentValidation Getting started documentation. In the next blog posts I will go into deeper validation of properties and reusing validators in different models.

Installation

For integration with ASP.NET Core, install the FluentValidation.AspNetCore package:

Basic validation

Using the package is very easy. Let’s say you have to following class:

You would define a set of validation rules for this class by inheriting from AbstractValidator:

To specify a validation rule for a particular property, call the RuleFor method, passing a lambda expression that indicates the property that you wish to validate. For example, to ensure that the Surname property is not null, the validator class would look like this:

To run the validator, instantiate the validator object and call the Validate method, passing in the object to validate.

The following code would write any validation failures to the console:

Deeper validation

In the next blog posts I will go into deeper validation of properties and reusing validators in different models.

One thought to “FluentValidation in ASP.NET Core”

Leave a Reply