| Muhammad Waseem

About Newsletter
Books
30 .NET Tips
Sponsorship
Fluent Validation in .NET
Apr 30, 2024
3 min read

Fluent Validation in .NET

Sponsor this Newsletter

If you are interested to learn this topic via video then check out this video :

Fluent Validation is a powerful library used in the .NET world. It provides much flexibility over validation, with the ability to add custom validations and many built-in validators.

We can install Fluent Validation using the NuGet Package Manager console with the following command

public sealed class Student
{
    public int Id { get; set; }
    public int RollNo { get; set; }
    public string FullName { get; set; }
    public string EmailAddress { get; set; }
}

How to create the first validator?

For example, we have Student classes:

using FluentValidation;

internal sealed class StudentValidator : AbstractValidator<Student>
{
    public StudentValidator()
    {
        RuleFor(x => x.FullName)
            .NotEmpty()
            .MinimumLength(5)
            .MaximumLength(100);
        RuleFor(x => x.Email)
            .NotEmpty()
            .EmailAddress(); // Built-in validation
    }
}

Now we have to define a validator by inheriting AbstarctValidator class from FluentValidation.

using FluentValidation;

internal sealed class StudentValidator : AbstractValidator<Student>
{
    public StudentValidator()
    {
        RuleFor(x => x.FullName)
            .NotEmpty()
            .MinimumLength(5)
            .MaximumLength(100);
        RuleFor(x => x.Email)
            .NotEmpty()
            .EmailAddress(); // Built-in validation
    }
}

I prefer to keep my validators sealed and internal

Registering Dependency of Validators

There are multiple ways to register dependencies of fluent validators.

  • Manual

  • Automatic

  • Manual Registration

services.AddScoped<IValidator<Student>, StudentValidator>();

When the number of validators increases this approach becomes difficult, and then we can shift towards the second approach it will automatically search all validators and register their dependencies.

  • Automatic Registration

It will scan the complete assembly and register the validators :

services
    .AddValidatorsFromAssembly(typeof(DependencyInjection).Assembly);

By default, these will be registered as Scoped, but we can customize lifetime scope and either include internals or not in this process like this :

services.AddValidatorsFromAssembly(
    includeInternalTypes: true,
    assembly: AssemblyReference.Assembly,
    lifetime: ServiceLifetime.Transient
);

How to use the validator?

We can use validators by injecting the IValidator and specifying the name of the class like this :

public class StudentService : IStudentService
{
    private readonly IValidator<Student> _validator;
    public StudentService(IValidator<Student> validator)
    {
        _validator = validator;
    }
    public async Task Save(Student student)
    {
        var validationResult = await _validator.ValidateAsync(student);
        // Add further logic to handle validationResult if needed
    }
}

ValidateAsync does the validation process and then by utilizing IsValid property we can figure out whether validation was successful or not.

We can call Validate or ValidateAsync as per need, in case of validation failure details can be found in the Errors property of the result.

This article was originally published at https://mwaseemzakir.substack.com/ on Apr 30, 2024 .

Whenever you're ready, there are 3 ways I can help you:

  1. Subscribe to my youtube channel : For in-depth tutorials, coding tips, and industry insights.
  2. Promote yourself to 9,000+ subscribers : By sponsoring this newsletter
  3. Patreon community : Get access to all of my blogs and articles at one place
Previous Next

Subscribe to Newsletter

Join 9,000 Software Engineers

Buy Me a Coffee

Enjoy my articles? Support me by buying a coffee!

Buy Me a Coffee

Muhammad Waseem

Resources
  • Books
  • Courses
Newsletter
  • Articles
  • Sponsorship
Books
  • 30 .NET Tips
  • 100 .NET Tips (Soon)
Author
  • About Us
  • Contact Us
Policy
  • Privacy Policy
  • Terms and Conditions
Interview
  • C# & .NET
  • Web API

Join my .NET newsletter and stay updated!

© 2025 Muhammad Waseem. All rights reserved.