Fluent Validation is a .NET library used to define validation rules for an object’s data. In the following post, I show the basic usage.

At first, you need to add FluentValidation.dll to your project.

For .NET Core use CLI command:

dotnet add package FluentValidation

However, if you are using NuGet run:

Install-Package FluentValidation

Validator

To illustrate a basic concept, I use example class that will help to introduce different rules.

public class Example {
  public string Text { get; set; }
  public int Number { get; set; }
  public List<object> Collection { get; set;}
}

In the beginning, we need someplace to store all validation rules. They are defined in the constructor of a class that inherits from AbstractValidator<T>. T is a type of object we are going to validate.

public class ExampleValidator : AbstractValidator<Example> {
  public ExampleValidator() {
    // Rules go here
  }
}

Rules

Next, for properties defined in the class, we can set different rules. Available validators depend on the chosen property type. There are few cases presented below that you can choose.

RuleFor(e => e.Text)
  .NotEmpty();

RuleFor(e => e.Text)
  .MaximumLength(100);

RuleFor(e => e.Number)
  .GreaterThanOrEqualTo(10);

Furthermore, you can find build-in validators here.

Adding rules definition for collection elements is also fairly straight forward.

RuleForEach(e => e.Collection)
  .NotNull();

Previously, presenting property validation I’ve set two different rules for Text. In fact, the Fluent Validation library provides rule chaining which works the same as two independent definitions and checks both criteria.

RuleFor(e => e.Text)
  .NotEmpty()
  .MaximumLength(100);

Usage

When we have all prepared it’s finally time to use it. So, to check objects against defined rules you need to call the Validate method.

namespace FluentValidationExample {
  public class Program {

    static void Main(string[] args) {
      var example = new Example {
        Number = 1,
        Text = "",
        Collection = new List<object>{new {X = "x"}, null}
      };

      var validator = new ExampleValidator();

      var result = validator.Validate(example);

      Console.WriteLine(result);
    }
  }
}

As a result, we receive ValidationResult which contains IsValid property and collection Errors with ValidationFailures. Each error has PropertyName, ErrorMessage, ErrorCode and more. In addition, the ToString method allows getting all failure messages, each in a new line.

For the presented example there are the following errors:

'Number' must be greater than or equal to '10'.
'Text' must not be empty.
'Collection' must not be empty.

On the other hand, you can throw an exception on validation error. Just instead of the Validate use ValidateAndThrow. It throws ValidationException if there is any error. The message of exception looks very similar.

Validation failed:
 -- Text: 'Text' must not be empty.
 -- Number: 'Number' must be greater than or equal to '10'.
 -- Collection[1]: 'Collection' must not be empty.

In the next post, I’ll cover some configuration such as rule execution strategy and message customization.