FluentValidation is a library that allows you to validate objects in a fluent and expressive way. With FluentValidation, you can create validation rules separate from your business logic, keeping your code clean and organized. The library is extensible and easy to use, supporting various forms of validation, such as required property checks, sizes, values, and more. In this example, we will see how to configure and use FluentValidation to validate a simple data class.
Libraries:
To use the FluentValidation library, install the following NuGet package in your project:
Install-Package FluentValidation
Example Code:
using FluentValidation;
using System;
public class Product
{
public string Name { get; set; }
public decimal Price { get; set; }
}
public class ProductValidator : AbstractValidator<Product>
{
public ProductValidator()
{
// Defining validation rules
RuleFor(p => p.Name)
.NotEmpty().WithMessage("The product name is required.")
.Length(3, 50).WithMessage("The product name must be between 3 and 50 characters.");
RuleFor(p => p.Price)
.GreaterThan(0).WithMessage("The price must be greater than zero.");
}
}
class Program
{
static void Main(string[] args)
{
// Creating a sample product
var product = new Product { Name = "Laptop", Price = -10 };
// Validating the product
var validator = new ProductValidator();
var results = validator.Validate(product);
if (!results.IsValid)
{
foreach (var error in results.Errors)
{
Console.WriteLine($"Error: {error.ErrorMessage}");
}
}
else
{
Console.WriteLine("Product is valid!");
}
}
}
Code Explanation:
In this example, we create a Product class with Name and Price properties. The ProductValidator class, which inherits from AbstractValidator, defines the validation rules for the Product object. We validate that the Name cannot be empty and must be between 3 and 50 characters, and that the Price must be greater than zero. In the Main method, we create a Product object with an invalid price value and then use the ProductValidator to validate the object. If there are validation errors, they are displayed in the console.
Conclusion:
FluentValidation is an excellent tool for validating objects in a fluent and clear way. It allows you to separate validation rules from business logic, resulting in a more organized and maintainable codebase. Its simple and extensible syntax makes it easy to create powerful and flexible validations for various scenarios.
Source code: GitHub
Top comments (0)