Performance is king (well, after accuracy) in APIs. Sending a request to the Database only to discover that the request is invalid is a waste of resources. Thus, we want to validate the request as soon as it hits the endpoint.
FluentValidation is a great tool for creating validators. It installs as a NuGet package. Also grab the version for ASP.Net.
To get going, add a using statement.
Using FluentValidation
Next, create a class that derives from AbstractValidator.
public class CarNotDeletedValidator : AbstractValidator<Car>
This example uses the Car class from my forthcoming book Creating .NET APIs with C#.
Put your validation rules in the constructor. Each rule is created by using the keyword RuleFor and a lambda expression that indicates which property you want to validate and the validation rule.
using Cars.Data.DTOs;
using FluentValidation;
namespace Cars.Validators
{
public class CarNotDeletedValidator : AbstractValidator<CarDto>
{
public CarNotDeletedValidator()
{
RuleFor(x => x.Is_Deleted).Equal("0");
}
}
}
The Equal operator is one of many that you can find at the FluentValidation documentation page: https://docs.fluentvalidation.net/en/latest/built-in-validators.html.
We’ll test the data and then either compare it to what is valid and return an error if appropriate, or, more commonly, we’ll throw an exception if the data fails validation.
Assuming that it passes validation we can continue to the Database. If however it fails, we can return a meaningful error to the sender.