Data Validation in ASP.NET Core with FluentValidation

Introduction

Data validation is a critical aspect of web application development. It ensures that the data entered by users is accurate, secure, and conforms to the expected format. In ASP.NET Core, FluentValidation provides a powerful and intuitive way to handle validation logic, making it easier for developers to validate user input and maintain clean, maintainable code.

What is FluentValidation in ASP.NET Core?

FluentValidation is a popular .NET library for building strongly typed validation rules. Unlike traditional attribute-based validation, FluentValidation offers a more expressive syntax and allows developers to define validation logic in a separate, clean, and reusable manner. It can be seamlessly integrated into ASP.NET Core applications, providing a robust solution for validating user input.

To use FluentValidation, start by creating an ASP.NET Core Web API project.

CreateNewProjects

After creating the project, you need to add 2 NuGet packages to it.

NuGet\Install-Package FluentValidation -Version 11.7.1
NuGet\Install-Package FluentValidation.DependencyInjectionExtensions -Version 11.7.1

After the installation process is complete, you will have the ability to establish validation rules for the models you create.

Creating Validation Rules

Consider a simple registration form with fields like username, email, and password. To validate this form, create a corresponding model and a validator class:

public class UserRegistrationModel
{
    public string Username { get; set; }
    public string Email { get; set; }
    public string Password { get; set; }
}

public class UserRegistrationValidator : AbstractValidator<UserRegistrationModel>
{
    public UserRegistrationValidator()
    {
        RuleFor(x => x.Username).NotEmpty().MinimumLength(3);
        RuleFor(x => x.Email).NotEmpty().EmailAddress();
        RuleFor(x => x.Password).NotEmpty().MinimumLength(6);
    }
}

In this example, UserRegistrationValidator defines rules for each property of the UserRegistrationModel.

Integrating FluentValidation with ASP.NET Core

To integrate FluentValidation with ASP.NET Core, add the validation rules to the Program.cs (in .Net 7.0)

builder.Services.AddScoped<IValidator<UserRegistrationModel>, UserRegistrationValidator>(); // register validators

Controller

ImplementingValidation in Controllers

Now, in your controller, you can use the validator to check the model's validity.

  [HttpPost]
    public IActionResult Register(UserRegistrationModel model)
    {
        var validator = new UserRegistrationValidator();
        var validationResult = validator.Validate(model);

        if (!validationResult.IsValid)
        {
            return BadRequest(validationResult.Errors);
        }

        // Process registration logic if the model is valid

        return Ok("Registration successful!");
    }

In this example, the Register action method used  UserRegistrationValidator to validate the incoming UserRegistrationModel. If the model is invalid, it returns a BadRequest response with the validation errors.

Please test this using Postman to ensure that it's working correctly. Let me know if you need any assistance with setting up the test.

PostmanWeather

It appears that the validation is functioning correctly now.

Conclusion

FluentValidation simplifies the process of data validation in ASP.NET Core applications. Providing a fluent and expressive API, allows developers to create complex validation rules in a readable and maintainable manner. By incorporating FluentValidation into your ASP.NET Core projects, you can ensure that your applications handle user input accurately and securely, leading to a more robust and reliable user experience.