Use FluentValidation In .NET Core

Background

Sometimes, there are many validation rules in our methods, such as the name cannot be null, the age must be greater than 18, etc., and as usual, we may write some code to define these rules. 

static void Main(string[] args)  
{  
    var addCusDto = new AddCustomerDto();  
    AddCustomer(addCusDto);  
    Console.ReadKey();  
}  
  
static void AddCustomer(AddCustomerDto dto)  
{  
    if (string.IsNullOrWhiteSpace(dto.Name))  
    {  
        Console.WriteLine($"name cannot be null");  
        return;  
    }  
  
    if (string.IsNullOrWhiteSpace(dto.Phone))  
    {  
        Console.WriteLine($"phone cannot be null");  
        return;  
    }  
  
    if (dto.Other <= 0)  
    {  
        Console.WriteLine($"other must great than 0");  
        return;  
    }   
    //save code ...  
}

However, this way seems not fluent. Here, I will introduce a small validation library named FluentValidation that uses a fluent interface and lambda expressions for building the validation rules.

FluentValidation is an open-source validation library for .NET applications that allows developers to easily define and enforce validation rules for their models and view models. The library uses fluent syntax to make it easy to express complex validation rules in a clear and concise way.

With FluentValidation, developers can define validation rules using a variety of built-in validators, such as NotNull, NotEmpty, MinimumLength, MaximumLength, and many others. They can also create custom validators by deriving from the Validator<T> base class and implementing the Validate method.

FluentValidation supports both server-side and client-side validation. Server-side validation is performed on the server and is used to ensure that data is valid before it is stored in a database or used to perform other operations. Client-side validation is performed in the user's browser and is used to provide real-time feedback to the user as they enter data into a form.

You can follow this link for more information.

https://fluentvalidation.net/

Let's take a look at how to use this library. Before the next section, we need to install FluentValidation via NuGet.

Step 1. Creating the validator

We need to create a class that inherits from AbstractValidator<T>, where T is the type of class that you wish to validate. For the background example, we can create the following validator.

public class AddCustomerDtoValidator : AbstractValidator<AddCustomerDto>  
{  
    public AddCustomerDtoValidator()  
    {  
        RuleFor(x => x.Name).NotEmpty().WithMessage("name cannot be null");  
        RuleFor(x => x.Phone).NotEmpty();  
        RuleFor(x => x.Other).GreaterThan(0).WithMessage("other must be great than 0");  
    }  
}

What does this validator do?

  1. The Name property is not empty. If this property is empty, the error message will be "name cannot be null".
  2. The Phone property is not empty. If this property is empty, the error message will be the default value.
  3. The Other property must be greater than 0. If this property is not greater than 0, the error message will be the default value.

Step 2. Using the validator

Now, let's use this

static void AddCustomerWithFluentValidation(AddCustomerDto dto)  
{  
    var validator = new AddCustomerDtoValidator();  
    var validRes = validator.Validate(dto);  
    if (!validRes.IsValid)  
    {  
        //first error message  
        Console.WriteLine(validRes.Errors.FirstOrDefault());  
        //Console.WriteLine(validRes.Errors.FirstOrDefault().ErrorMessage);  
        ////all error messages  
        //Console.WriteLine(validRes.ToString(","));  
        //Console.WriteLine(string.Join(",", validRes.Errors.Select(x => x.ErrorMessage)));  
        //Console.WriteLine(string.Join(",", validRes.Errors));  
    }  
  
    //save code ...  
}

As you can see, we just created an instance of the validator and called the Validatmethod by passing the dto object we want to validate.

The Validate method returns a ValidationResult object. It contains two properties; one is IsValid which says whether the validation succeeded or not, while the other one is Errors, which contains the details about any validation failures.

The above sample shows you how to get the first error message and all error messages. You can return the message(s) based on your requirement. We only need two steps to use this library.

There are many useful features of FluentValidation, such as chaining validators.

RuleFor(x => x.Name)
      .NotEmpty()
      .NotEqual("catcher")
      .WithMessage("name cannot be null");  

We can combine lots of validators for a property.

Summary

This article introduced a new way to build the validation rules.

I hope this will help you!


Similar Articles