FluentValidation in .NET 8

What is FluentValidation?

FluentValidation is an open-source validation library for .NET that provides a fluent interface for defining and executing validation rules. It allows developers to express validation logic in a clear and concise manner, making it easy to read, write, and maintain.

FluentValidation in .NET 8

To get started with FluentValidation in .NET 8, you need to install the FluentValidation NuGet package. You can do this using the following command in the Package Manager Console or the .NET CLI:

dotnet add package FluentValidation

Validating a Simple User Model

Let's create a simple example where we have a User class that we want to validate. We'll use FluentValidation to ensure that the user's name is not empty and their email address is valid.

using FluentValidation;

public class User
{
    public string Name { get; set; }
    public string Email { get; set; }
}

public class UserValidator : AbstractValidator<User>
{
    public UserValidator()
    {
        RuleFor(user => user.Name).NotEmpty().WithMessage("Name cannot be empty");
        RuleFor(user => user.Email).NotEmpty().EmailAddress().WithMessage("Invalid email address");
    }
}

In this example:

  • We define a User class with properties for Name and Email.
  • We create a UserValidator class that inherits from AbstractValidator<User>.
  • Inside the UserValidator constructor, we use the RuleFor method to specify validation rules for the Name and Email properties.

Using FluentValidation in Your Application

Now that we have our User class and corresponding validator, let's see how we can use FluentValidation in our application:

class Program
{
    static void Main()
    {
        var user = new User { Name = "Mahesh Chand", Email = "[email protected]" };
        var validator = new UserValidator();

        var validationResult = validator.Validate(user);

        if (validationResult.IsValid)
        {
            Console.WriteLine("User is valid");
        }
        else
        {
            foreach (var error in validationResult.Errors)
            {
                Console.WriteLine($"Validation Error: {error.ErrorMessage}");
            }
        }
    }
}

In this example:

  • We create an instance of the User class and set its properties.
  • We create an instance of the UserValidator class.
  • We call the Validate method on the validator, passing in the User instance.
  • We check if the validation result is valid. If it is, we print a success message. Otherwise, we iterate over the errors and print them.

Conclusion

FluentValidation in .NET 8 provides a clean and expressive way to handle validation in your applications. With its fluent interface and easy-to-understand syntax, you can define and execute validation rules with confidence. As shown in our example, using FluentValidation allows you to keep your validation logic separate from your business logic, promoting a more maintainable and readable codebase.

😊Please consider liking and following me for more articles and if you find this content helpful.πŸ‘


Citiustech Healthcare Technology Pvt Ltd
CitiusTech plays a deep and meaningful role in powering the future of healthcare.