Elevating Data Quality: A Dive into FluentValidation's Mastery

October 19, 2023 by Pierre Belin

Data quality is the cornerstone of efficient software applications, and ensuring impeccable data input becomes imperative as applications grow complex. FluentValidation emerges as a stalwart companion for .NET developers, delivering precision in data validation with unparalleled ease.

Nestled within the .NET ecosystem is FluentValidation, a revered open-source library crafted for crafting precise validation rules. It has garnered admiration for its straightforward, fluent interface, ease of scalability, and how effortlessly it facilitates creating and maintaining data validation rules. Thanks to the commitment of its active development community, it remains at the forefront of modern development practices.

How to use it

The beauty of FluentValidation lies in its simplicity, such as the `RuleFor` method. This method provides a clear path to target specific object properties, easily layering on validations. Here, we've emphasized the importance of naming our clients, age restrictions, and validating them. Adding clarity, the `.WithMessage()` method offers tailored error messages to guide the user.


RuleFor(client=> client.Firstname)
.Must(name => client.StartsWith("D"))
.When(client=> client.Age < 28)
.WithMessage("It is impossible to have less than 28yo with firstname not starting with a D.");

Post-creation, the application of the validator is remarkably straightforward, leveraging the `Validate` method:


var client = new Client { Firstname = "Ted", Lastname = "Buddy", Age = 25 };
var validator = new ClientValidator();
var validationResult = validator.Validate(client);

The resultant validation provides a comprehensive report detailing every model applied to the input object. Each rule's adherence is meticulously checked, capturing discrepancies along the way.

Utilizing the `IsValid` property, developers gain instant insights into the validation's outcome:


if (validationResult.IsValid)
{
    // Undertake subsequent actions.
}
else
{
    // Gracefully handle any validation exceptions.
    foreach (var failure in validationResult.Errors)
    {
        Console.WriteLine($"The {failure.PropertyName} encountered a hiccup. Here's what went wrong: {failure.ErrorMessage}");
    }
}

Improve rules complexity

For the more curious developers, FluentValidation doesn't stop here.

The `.When()` method offers conditional validation, allowing developers to execute validation rules only when specified conditions are met. This is particularly helpful when validation requirements are contingent on other property values or external factors.

Imagine a scenario where a client's state changes based on its age. A client under 18 must be a minor, while the others are adults:


RuleFor(client => client.State)
.Equal(StateType.Minor)
.When(client=> client.Age < 18)
.WithMessage("Client should be minor if age is under 18.");

In data validation, sometimes the raw input data isn't in the ideal format for validation. Instead of resorting to pre-processing or creating temporary objects, FluentValidation offers the `.Transform()` method. This method allows developers to alter a value before it's validated, ensuring the validator gets data in the exact shape it needs.

For instance, suppose user input comes with leading or trailing white spaces. Before validating, we can trim the input to reduce the complexity of our rule:


RuleFor(client=> client.Lastname)
.Transform(client=> client?.Trim())    
.NotEmpty()
.WithMessage("A client's name cannot be blank.");

Additionally, for those instances where standard rules fall short, FluentValidation empowers developers with custom validator capabilities, allowing them to handcraft specific validation logic.

Summary

FluentValidation is more than just a validation tool; it symbolizes excellence in the .NET universe. Blending traditional validation rules with nuanced, detailed checks, the library guarantees that every data input stands up to scrutiny. In the dynamic world of software, every data point is pivotal. With FluentValidation in one's toolkit, developers can ensure seamless operations and circumvent potential data pitfalls.

Check out the project: https://github.com/FluentValidation/FluentValidation