avatarAshish Patel

Summary

This context provides a guide on how to use FluentValidation in ASP.NET and ASP.NET Core applications for model validation.

Abstract

The context discusses the importance of data validation in applications and introduces FluentValidation as a replacement for existing validation attributes (Data Annotations) in ASP.NET and ASP.NET Core applications. FluentValidation separates validation rules and/or logic from the Model/DTO classes, making the model classes clean and readable. The guide explains how to configure FluentValidation in ASP.NET Core by installing NuGet packages, setting up the configuration, and defining a set of validation rules for a particular object. It also highlights the features of FluentValidation, such as built-in validators, custom validators, localization, test extensions, asynchronous validation, and transforming values.

Bullet points

  • Data validation is essential for any application.
  • FluentValidation is a library that helps in making validations clean, easy to create, and maintain.
  • It separates the validation rules and/or logic from the Model/DTO classes.
  • To use FluentValidation, you need to install the FluentValidation.AspNetCore and FluentValidation.DependencyInjectionExtensions NuGet packages.
  • You can define a set of validation rules for a particular object by creating a class that inherits from AbstractValidator<T>, where T is the type of class that you wish to validate.
  • The validation rules themselves should be defined in the validator class’s constructor.
  • FluentValidation provides several built-in validators like Regular Expression, Email, Credit Card, and many more.
  • You can create a custom, reusable validator using FluentValidation.
  • FluentValidation provides translations for the default validation messages in several languages.
  • You can define asynchronous rules when working with an external API.
  • You can apply a transformation to a property value prior to validation being performed against it.
  • FluentValidation provides better control of validation rules and makes validation rules easy to read, easy to test, and enable great separation of concerns.

Use FluentValidation in ASP.NET or ASP.NET Core

Getting started — How to use Fluent Validation in .NET and .NET Core?

FluentValidation in .NET

TL;DR

FluentValidation is a popular .NET library for building strongly-typed validation rules. It is a small validation library that uses a fluent interface and lambda expressions for building validation rules.

Most popular .NET Libraries every developer should know.

Introduction to FluentValidation

Data Validation is essential for any Application. When it comes to Validating Models, developers usually use Data Annotations. There are few issues with Data Annotations approach: 1. Validation rules are tightly coupled with models. 2. Add complexity to Models/DTOs. 3. Difficult to make dynamic and conditional validations. 4. Difficult to extend and scale.

FluentValidation is a replacement for the existing validation attributes (Data Annotations). It can turn up the validation game to a new level, gives total control. It separates the validation rules and/or logic from the Model/DTO classes.

It is a open-source library that helps you make validations clean, easy to create, and maintain. It also works on external models that you don’t have access. It makes the model classes clean and readable .

Configure FluentValidation in ASP.NET Core

1. NuGet: To use FluentValidation, you need to install below NuGet packages.

PM> Install-Package FluentValidation.AspNetCore
PM> Install-Package FluentValidation.DependencyInjectionExtensions

2. Configuration: Automatic registration of validators is possible. You can make use of the FluentValidation.DependencyInjectionExtensions package which can be used to automatically find all the validators in a specific assembly using an extension method.

This adds FluentValidation to the pipeline for Controllers.

Validator

To define a set of validation rules for a particular object, you will need to create a class that inherits from AbstractValidator<T>, where T is the type of class that you wish to validate.

The validation rules themselves should be defined in the validator class’s constructor. 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.

  • You can use the RuleForEach method to apply the same rule to multiple items in a collection.
  • You can also combine RuleForEach with SetValidator when the collection is of another complex objects.
  • RuleSets allow you to group validation rules together which can be executed together as a group whilst ignoring other rules.
  • Including Rules: You can include rules from other validators provided they validate the same type. This allows you to split rules across multiple classes and compose them together.
  • Validators can be used with any dependency injection library. To inject a validator for a specific model, you should register the validator with the service provider as IValidator<T>. services.AddScoped<IValidator<Customer>, CustomerValidator>();

3. Usage: You don’t need to explicitly check the ModelState in controllers to see if the input is valid. The FluentValidation ASP.NET middleware will automatically find our validator, and if validation fails it will prepare the ModelState and our action will return a 400 response.

You can also explicitaly validate the models anywhere. The Validate method returns a ValidationResult object. This contains two properties:

  • IsValid - a boolean that says whether the validation suceeded.
  • Errors - a collection of ValidationFailure objects containing details about any validation failures.

FluentValidation Features

  • Built-in Validators — ships with several built-in validators like Regular Expression, Email, Credit Card, and many more.
  • Custom Validators — There are several ways to create a custom, reusable validator.
  • Localization — provides translations for the default validation messages in several languages.
  • Test Extensions — provides some extensions that can aid with testing your validator classes.
  • Asynchronous Validation — you can define asynchronous rules, for example when working with an external API.
  • Transforming Values — you can apply a transformation to a property value prior to validation being performed against it.

Sample source code on GitHub.

Summary

FluentValidation provides a great alternative to Data Annotations in order to validate models. It gives better control of validation rules and makes validation rules easy to read, easy to test, and enable great separation of concerns.

View more from .NET Hub

Happy Coding!!!

Dotnet
Fluent Validation
Aspnetcore
Dotnet Core
Fluentvalidator
Recommended from ReadMedium