ASP.NET Core Fluent Validation and why will it always be important

Code

April 29, 2024

Validation is a process to validate and check the data inserted by the user. Every MVC application needs some kind of validation, either for the DTO model or Entity. So why not use Fluent Validation?

Fluent Validation is a .NET library that uses lambda expressions for building validation rulers. Using Fluent Validation you can create some advance and complex validation for the user data. Let’s get it started.

First, from the command line or NuGet package manager install FluentValidation.AspNetCore.

For ASP.NET to discover your validators, they must be registered with the services collection. The best way to do that is by using the RegisterValidationsFromAssemblyContaining method to automatically register all validators within a particular assembly. This will automatically find any public, non-abstract types that inherit from AbstractValidator and register them with the container

services.AddControllers().AddFluentValidation(fv =>fv.RegisterValidatorsFromAssemblyContaining<Startup>());

Validate incoming request

This next example assumes that the UserValidator is defined to validate a class called User.

public class User
{
   public string Name { get; set; }
   public string Email { get; set; }
   public int Age { get; set; }
}

public class UserValidator : AbstractValidator<User>
{
   public UserValidator()
   {
       RuleFor(x => x.Name).Length(0, 10);
       RuleFor(x => x.Email).EmailAddress();
   }
}

When you send a post request, MVC’s model-binding infrastructure will validate the User object with UserValidator. If a request is not valid, you get response messages with corresponding errors which are shown below.

Corresponding errors

Custom Validators

With plenty of built-in validators, Fluent Validator offers custom validators. The recommended way is to make use of the Predicate Validator to write a custom validation function. The simplest way to implement a validator is by using Must method, which internally uses the PredicateValidator.

public class User
{
   public IList<string> FavoriteColors;
}
public class UserValidator : AbstractValidator<User>
{
   public UserValidator()
   {
       RuleFor(x => x.FavoriteColors)
           .Must(list => list.Contains("Blue"))
           .WithMessage("The list must contain Blue color").
   }
}

To make this logic reusable, we can wrap it in an extension method that acts upon any List<string> type.

public static class MyCustomValidators {
public static IRuleBuilderOptions<T, IList<string>>    ListMustContainColor<T>(this IRuleBuilder<T, IList<string>> ruleBuilder, string color)
{
  return ruleBuilder
       .Must(list => list.Contains(color))
       .WithMessage("The list does not contain color " + color);
  }
}

Our rule definition can now be rewritten to use our custom method.

RuleFor(x => x.FavoriteColors).ListMustContainColor("Blue");

Conclusion

Fluent Validation is a powerful tool to validate DTOs, entities, etc. Using this validator you can write simpler and more cleaner code. For more cool stuff feel free to visit the official Fluent Validation documentation.

ready to talk