A Professional ASP.NET Core API - FluentValidation
FluentValidation
is a A .NET library for building strongly-typed validation rules. It uses lambda expressions for building validation rules for your business objects.
If you want to do simple validation in asp.net mvc application then data annotations validation is good but in case if you want to implement complex validation then you need to use FluentValidation
.
In the following we will see how it can be added to a project and how it works.
Install the below packages
1 | Install-Package FluentValidation -Version 9.2.2 |
Register FluentValidation
as following
1 | public void ConfigureServices(IServiceCollection services) |
In order for ASP.NET to discover your validators, they must be registered with the services collection. You can either do this by calling the AddTransient
method for each of your validators:
1 | public void ConfigureServices(IServiceCollection services) |
Using the validator in a controller
1 | public class Person { |
We can use the Person class within our controller and associated view:
1 | [ ] |
Now, If you call the Create
API with above JSON
data you will see the below result
1 | { |
Automatic Registration
You can also use the below methods to automatically register all validators within a particular assembly. This will automatically find any public, non-abstract types that inherit from AbstractValidator
and register them with the container (open generics are not supported).
1 | public void ConfigureServices(IServiceCollection services) |
Compatibility with ASP.NET’s built-in Validation
By default, after FluentValidation
is executed, any other validator providers will also have a chance to execute. This means you can mix FluentValidation
with DataAnnotations
attributes (or any other ASP.NET ModelValidatorProvider
implementation).
If you want to disable this behaviour so that FluentValidation
is the only validation library that executes, you can set the RunDefaultMvcValidationAfterFluentValidationExecutes
to false
in your application startup routine:
1 | public void ConfigureServices(IServiceCollection services) |
Built-in Validators
NotNull ("NotNull")
: to check the property is null.NotEmpty ("NotEmpty")
: to check the property is null, empty or has whitespace.NotEqual ("NotEqual")
: to check the specified property is not equal to a particular value.Equal Validator ("Equal")
: to check the value of the specified property is equal to a particular value.Length Validator ("Length")
: to check the length of a particular string property is within the specified range.MaxLength Validator ("MaximumLength")
: to check the length of a particular string property is no longer than the * specified value.MinLength Validator ("MinimumLength")
: to check the length of a particular string property is longer than the * specified value.Less Than Validator ("LessThan")
: to check the length of the specified property is less than a particular valueLessThanOrEqual Validator ("LessThanOrEqualTo")
: to check the value of the specified property is less than or * equal to a particular value.Greater Than Validator ("GreaterThan")
: to check the value of the specified property is greater than a particular * value.Regular Expression Validator ("Matches")
: to check the value of the specified property matches the given regular * expression.Email Validator Validator ("EmailAddress")
: to check the value of the specified property is a valid email address.
Implicit vs Explicit Child Property Validation
When validating complex object graphs, by default, you must explicitly specify any child validators for complex properties by using SetValidator
.
When running an ASP.NET MVC application, you can also optionally enable implicit validation for child properties. When this is enabled, instead of having to specify child validators using SetValidator
, MVC’s validation infrastructure will recursively attempt to automatically find validators for each property. This can be done by setting ImplicitlyValidateChildProperties
to true:
1 | public void ConfigureServices(IServiceCollection services) |
Manual validation
Sometimes you may want to manually validate an object in a MVC project. In this case, the validation results can be copied to MVC’s modelstate dictionary:
1 | [ ] |
Custom messages
We can extend the above example to include a more useful error message. At the moment, our custom validator always returns the message “The list contains too many items” if validation fails. Instead, let’s change the message so it returns “’Pets’ must contain fewer than 10 items.” This can be done by using custom message placeholders. FluentValidation supports several message placeholders by default including {PropertyName} and {PropertyValue} (see this list for more), but we can also add our own.
1 | public class PersonValidator : AbstractValidator<Person> { |
Localization
You can add IStringLocalizer<T>
to the ctor
of a validator
1 | public class PersonValidator : AbstractValidator<Person> |
And these are our resources
1 | // person.en-US.json |
Swagger integration
Use FluentValidation
rules instead of ComponentModel
attributes to define swagger schema.
Install below package
1 | Install-Package MicroElements.Swashbuckle.FluentValidation -Version 4.0.0 |
Change Startup.cs
as following
1 | // Startup.cs |
Extensibility
You can register FluentValidationRule
in ServiceCollection
.
User defined rule name replaces default rule with the same. Full list of default rules can be get by FluentValidationRules.CreateDefaultRules()
List or default rules:
- Required
- NotEmpty
- Length
- Pattern
- Comparison
- Between
- Example of rule:
1 | new FluentValidationRule("Pattern") |
Reference(s)
Most of the information in this article has gathered from various references.