Validot is a performance-first, compact library for advanced model validation. Using a simple declarative fluent interface, it efficiently handles classes, stru
Validot is a performance-first, compact library for advanced model validation. Using a simple declarative fluent interface, it efficiently handles classes, stru
Validot
Validot is a performance-first, compact library for advanced model validation. Using a simple declarative fluent interface, it efficiently handles classes, structs, nested members, collections, nullables, plus any relation or combination of them. It also supports translations, custom logic extensions with tests, and DI containers.
⚔️ Validot vs FluentValidation ⚔️
Article: Validot's performance explained
Article: Crafting model specifications using Validot
Built with by Bartosz LenarValidot has been my public pet project since 2020, a proof-of-concept turned into a standalone, fully-featured NuGet library. Its core focus is on performance and a low-allocation approach. On release day, Validot was 2.5 times faster while consuming 8 times less memory than the industry's gold standard: FluentValidation! I pushed dotnet memory performance and optimizations to their limits. And I'm proud of my work.
Given my daily responsibilities and other coding projects, I have to confess that it seems improbable I'll have time to keep working on Validot.
I appreciate all the contributors, and especially, I extend my gratitude to Jeremy Skinner for his work on FluentValidation. I genuinely believe I played a role in the open source community by motivating Jeremy to enhance FluentValidation's performance.
Add the Validot nuget package to your project using dotnet CLI:
dotnet add package ValidotAll the features are accessible after referencing single namespace:
using Validot;And you're good to go! At first, create a specification for your model with the fluent api.
Specification specification = _ => _
.Member(m => m.Email, m => m
.Email()
.WithExtraCode("ERR_EMAIL")
.And()
.MaxLength(100)
)
.Member(m => m.Name, m => m
.Optional()
.And()
.LengthBetween(8, 100)
.And()
.Rule(name => name.All(char.IsLetterOrDigit))
.WithMessage("Must contain only letter or digits")
)
.And()
.Rule(m => m.Age >= 18 || m.Name != null)
.WithPath("Name")
.WithMessage("Required for underaged user")
.WithExtraCode("ERR_NAME");The next step is to create a validator. As its name stands - it validates objects according to the specification. It's also thread-safe so you can seamlessly register it as a singleton in your DI container.
var validator = Validator.Factory.Create(specification);Validate the object!
var model = new UserModel(email: "inv@lidv@lue", age: 14);
var result = validator.Validate(model);The result object contains all information about the errors. Without retriggering the validation process, you can extract the desired form of an output.
result.AnyErrors; // bool flag:
// true
result.MessageMap["Email"] // collection of messages for "Email":
// [ "Must be a valid email address" ]
result.Codes; // collection of all the codes from the model:
// [ "ERR_EMAIL", "ERR_NAME" ]
result.ToString(); // compact printing of codes and messages:
// ERR_EMAIL, ERR_NAME
//
// Email: Must be a valid email address
// Name: Required for underaged userNo more obligatory if-ology around input models or separate classes wrapping just validation logic. Write specifications inline with simple, human-readable fluent API. Native support for properties and fields, structs and classes, nullables, collections, nested members, and possible combinations.
…Compact, highly optimized, and thread-safe objects to handle the validation.
Specification bookSpecification = s => s
.Optional()
.Member(m => m.AuthorEmail, m => m.Optional().Email())
.Member(m => m.Title, m => m.NotEmpty().LengthBetween(1, 100))
.Member(m => m.Price, m => m.NonNegative());
var bookValidator = Validator.Factory.Create(bookSpecification);
services.AddSingleton>(bookValidator);…Whatever you want. Error flag, compact list of codes, or detailed maps of messages and codes. With sugar on top: friendly ToString() printing that contains everything, nicely formatted.
…Tons of rules available out of the box. Plus, an easy way to define your own with the full support of Validot internal features like formattable message arguments.
public static IRuleOut ExactLinesCount(this IRuleIn @this, int count)
{
return @this.RuleTemplate(
value => value.Split(Environment.NewLine).Length == count,
"Must contain exactly {count} lines",
Arg.Number("count", count)
);
}.ExactLinesCount(4)
// Must contain exactly 4 lines
.ExactLinesCount(4).WithMessage("Required lines count: {count}")
// Required lines count: 4
.ExactLinesCount(4).WithMessage("Required lines count: {count|format=000.00|culture=pl-PL}")
// Required lines count: 004,00Pass errors directly to the end-users in the language of your application.
…At the moment Validot delivers the following translations out of the box: Polish, Spanish, Russian, Portuguese and German.
Although Validot doesn't contain direct support for the dependency injection containers (because it aims to rely solely on the .NET Standard 2.0), it includes helpers that can be used with any DI/IoC system.
For example, if you're working with ASP.NET Core and looking for an easy way to register all of your validators with a single call (something like services.AddValidators()), wrap your specifications in the specification holders, and use the following snippet:
…AddValidators extension step-by-stepA short statement to start with - @JeremySkinner's FluentValidation is an excellent piece of work and has been a huge inspiration for this project. True, you can call Validot a direct competitor, but it differs in some fundamental decisions, and lot of attention has been focused on entirely different aspects. If - after reading this section - you think you can bear another approach, api and limitations, at least give Validot a try. You might be positively surprised. Otherwise, FluentValidation is a good, safe choice, as Validot is certainly less hackable, and achieving some particular goals might be either difficult or impossible.
This document shows oversimplified results of BenchmarkDotNet execution, but the intention is to present the general trend only. To have truly reliable numbers, I highly encourage you to run the benchmarks yourself.
There are three data sets, 10k models each; ManyErrors (every model has many errors), HalfErrors (circa 60% have errors, the rest are valid), NoErrors (all are valid) and the rules reflect each other as much as technically possible. I did my best to make sure that the tests are just and adequate, but I'm a human being and I make mistakes. Really, if you spot errors in the code, framework usage, applied methodology... or if you can provide any counterexample proving that Validot struggles with some particular scenarios - I'd be very very very happy to accept a PR and/or discuss it on GitHub Issues.
To the point; the statement in the header is true, but it doesn't come for free. Wherever possible and justified, Validot chooses performance and less allocations over flexibility and extra features. Fine with that kind of trade-off? Good, because the validation process in Validot might be ~1.6x faster while consuming ~4.7x less memory (in the most representational, Validate tests using HalfErrors data set). Especially when it comes to memory consumption, Validot could be even 13.3x better than FluentValidation (IsValid tests with HalfErrors data set) . What's the secret? Read my blog post: Validot's performance explained.
| Test | Data set | Library | Mean [ms] | Allocated [MB] |
|---|---|---|---|---|
| Validate | ManyErrors |
FluentValidation | 703.83 |
453 |
| Validate | ManyErrors |
Validot | 307.04 |
173 |
| FailFast | ManyErrors |
FluentValidation | 21.63 |
21 |
| FailFast | ManyErrors |
Validot | 16.76 |
32 |
| Validate | HalfErrors |
FluentValidation | 563.92 |
362 |
| Validate | HalfErrors |
Validot | 271.62 |
81 |
| FailFast | HalfErrors |
FluentValidation | 374.90 |
249 |
| FailFast | HalfErrors |
Validot | 173.41 |
62 |
| Validate | NoErrors |
FluentValidation | 559.77 |
354 |
| Validate | NoErrors |
Validot | 260.99 |
75 |
FluentValidation's IsValid is a property that wraps a simple check whether the validation result contains errors or not. Valid
No open issues yet, or sync has not completed.