Validation with FluentValidation in .NET Core 8.0

Introduction

Validation is a critical aspect of application development, ensuring that data meets certain criteria before being processed. In the world of .NET Core, FluentValidation stands out as a powerful and expressive library for crafting validation rules.

In this comprehensive blog, we'll delve into FluentValidation, explore its features, and walk through real-world examples using C# code snippets.

What is FluentValidation?

FluentValidation is an open-source .NET library that provides a fluent interface for defining and executing validation rules. It enables developers to express complex validation logic in a clear and readable manner.

Key Features of FluentValidation

  1. Fluent API: The library employs a fluent and expressive syntax for defining validation rules, making the code easy to read and maintain.
  2. Separation of Concerns: FluentValidation encourages the separation of validation logic from the business entities, promoting a clean and modular design.
  3. Extensibility: Developers can easily extend FluentValidation by creating custom validators and validation rules tailored to their application's requirements.
  4. Integration with ASP.NET Core: FluentValidation integrates seamlessly with ASP.NET Core, simplifying the validation of user input in web applications.

Getting Started with FluentValidation in .NET Core 8.0


Installation

To use FluentValidation in your .NET Core project, start by installing the FluentValidation NuGet package.

dotnet add package FluentValidation

Defining Validators

Create a validator class for your model, inheriting from AbstractValidator<T>.

public class PersonValidator : AbstractValidator<Person>
{
    public PersonValidator()
    {
        RuleFor(person => person.FirstName).NotEmpty().WithMessage("First name is required.");
        RuleFor(person => person.Age).InclusiveBetween(18, 99).WithMessage("Age must be between 18 and 99.");
    }
}

Using Validators

In your application code, instantiate the validator and use it to validate objects.

var person = new Person { FirstName = "", Age = 16 };
var validator = new PersonValidator();

var validationResult = validator.Validate(person);

if (!validationResult.IsValid)
{
    foreach (var error in validationResult.Errors)
    {
        Console.WriteLine($"Property: {error.PropertyName}, Error: {error.ErrorMessage}");
    }
}

Example 1. Validating User Registration

Consider a scenario where you need to validate user registration data in an ASP.NET Core application.

public class RegistrationViewModelValidator : AbstractValidator<RegistrationViewModel>
{
    public RegistrationViewModelValidator()
    {
        RuleFor(model => model.Username).NotEmpty().MinimumLength(5).MaximumLength(20);
        RuleFor(model => model.Email).NotEmpty().EmailAddress();
        RuleFor(model => model.Password).NotEmpty().MinimumLength(8);
        // Add additional rules as needed
    }
}

Example 2. Validating Product Information

In an e-commerce application, you might want to ensure that product information is valid.

public class ProductValidator : AbstractValidator<Product>
{
    public ProductValidator()
    {
        RuleFor(product => product.Name).NotEmpty();
        RuleFor(product => product.Price).GreaterThan(0);
        RuleFor(product => product.QuantityInStock).GreaterThanOrEqualTo(0);
        // Add more rules for other properties
    }
}

Conclusion

FluentValidation in .NET Core 8.0 provides a robust and elegant solution for implementing validation rules in your applications. Its fluent API empowers developers to express complex validation logic in a readable and maintainable way. By separating validation concerns, extending capabilities, and seamlessly integrating with ASP.NET Core, FluentValidation emerges as a valuable tool in the toolkit of modern .NET developers. As you embark on your validation journey, consider FluentValidation as a companion to ensure your data meets the highest standards.

Happy validating!