validly by Roman Jambor
NuGet / site data
Details
Info
Name: validly
Powerful, efficient, and highly customizable validation library for .NET, leveraging the capabilities of C# Source Generators to provide compile-time validation logic generation.
Author: Roman Jambor
NuGet: https://www.nuget.org/packages/validly/
You can find more details at https://github.com/Hookyns/validly
Author
Roman Jambor
Original Readme
Validly
This repository contains a powerful, efficient, and highly customizable validation library for .NET, leveraging the capabilities of C# Source Generators to provide compile-time validation logic generation. The library is designed to simplify model validation in .NET applications by automatically generating validation code based on attributes and custom rules, reducing runtime overhead and enhancing code maintainability.
Key Features
- Compile-Time Code Generation: Uses C# Source Generators to create validation code at compile-time, eliminating the need for runtime reflection and improving performance.
- Attribute-Based Validation: Define validation rules using simple attributes directly on your models, allowing clear and maintainable validation rules.
- Property and Object-Level Validation: Supports validation of individual properties as well as the model as a whole, enabling both fine-grained and aggregate validations.
- Customizable Validation Logic: Extend the library with custom validation attributes and rules to meet unique validation requirements.
- Detailed Validation Results: Provides rich validation results, including per-property error messages and model-wide validation summaries.
- Seamless Integration: Designed to work smoothly in .NET applications, with support for dependency injection and easy configuration.
Getting Started
To start using the library, add it to your project as a NuGet package. Decorate your model with [Validatable]
attribute and properties with validation attributes and let the source generator handle the rest. Generated code will include optimized validation methods that you can call to validate instances of your models.
Example Usage
Define validation rules using attributes on your model properties:
[Validatable]
public partial class CreateUserRequest
{
[Required]
[MinLength(3)]
[MaxLength(100)]
public string Name \{ get; set; }
[Required]
[EmailAddress]
public string Email \{ get; set; }
[Range(18, 99)]
public int Age \{ get; set; }
}
Validate the model in your application code:
app.MapPost("/users", async (CreateUserRequest request) =>
{
var validationResult = request.Validate(); // This method is generated by the source generator
if (!validationResult.IsSuccess)
{
return Results.BadRequest(validationResult);
}
// create user...
return Results.Created($"/users/{user.Id}");
});
Installation
Install the package via NuGet:
dotnet add package Validly
Install the source generator package to enable compile-time validation code generation:
dotnet add package Validly.SourceGenerator
Install the package with default validators:
dotnet add package Validly.Extensions.Validators
Why Validly? Why Attribute-Based Validation?
Validly was born out of the need for a simple, performant way to handle validations in applications, particularly when following Domain-Driven Design (DDD). In DDD, entities are responsible for their own validation. While validations on the API level are important, they cannot be the sole safeguard. The domain must validate entities independently, as the API is just one entry point to your system. Other sources, like background jobs or message queues, can also create or interact with domain objects.
Humans make mistakes, and developers are no exception. Relying solely on API-level validations is risky; you need a robust validation layer directly in your domain to ensure data integrity across all interactions.
Why Not Existing Libraries?
Libraries like FluentValidation are powerful, but they have limitations:
- Reflection-based design: While flexible, this approach bypasses static code analysis, making your code harder to refactor and less performant.
- Complexity: These libraries often require additional boilerplate code and are more suited to abstract validation pipelines, such as middleware in an API, than to domain entities.
Validly solves these issues by offering an attribute-based, source-generator-powered approach for validations. It combines simplicity, static analysis support, and high performance, making it an ideal choice for both API-level and domain-level validation.
Why Attribute-Based Validation?
Most validations are straightforward and can be expressed cleanly with attributes. For example, validating that a string is not empty or a number falls within a range shouldn’t require excessive boilerplate. Attributes allow you to express such requirements concisely and directly within your model.
Separating validations from the model may even be considered an anti-pattern or a violation of the Single Responsibility Principle. When validations are defined externally, it increases the likelihood of developer errors—such as forgetting to update validations when the model changes. By keeping validations close to the model, Validly ensures consistency, simplifies maintenance, and minimizes mistakes.
Contributors
Roman Jámbor 💻 🚧 📖 👀 💡 🤔 🚇 💬 ⚠️ | Whitepalko 💻 🤔 | TallasDev 🤔 | completezero ⚠️ | Степан 💻 |
License
This project is licensed under the MIT License.
This .NET validation library aims to streamline validation in .NET applications, leveraging modern C# features for performance and ease of use. It’s ideal for developers looking to minimize boilerplate code and maximize performance in their validation routines.
About
Generates validation code for C# classes based on attributes.
How to use
Example (source csproj, source files)
- CSharp Project
- Program.cs
- Person.cs
This is the CSharp Project that references validly
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net9.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<PropertyGroup>
<EmitCompilerGeneratedFiles>true</EmitCompilerGeneratedFiles>
<CompilerGeneratedFilesOutputPath>$(BaseIntermediateOutputPath)\GX</CompilerGeneratedFilesOutputPath>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Validly" Version="1.1.5" />
<PackageReference Include="Validly.Extensions.Validators" Version="1.1.3" />
<PackageReference Include="Validly.SourceGenerator" Version="1.1.5" />
</ItemGroup>
</Project>
This is the use of validly in Program.cs
// See https://aka.ms/new-console-template for more information
using Valid;
Console.WriteLine("Hello, World!");
Person p= new (){ Age = 55, Name = "Andrei" };
p.Validate();
Console.WriteLine("Person is valid");
This is the use of validly in Person.cs
using System.ComponentModel.DataAnnotations;
using Validly;
namespace Valid;
[Validatable]
public partial class Person
{
[Range(18, 199)]
public int Age \{ get; set; }
[Required]
[MinLength(3)]
public string Name \{ get; set; \} = string.Empty;
}
Generated Files
Those are taken from $(BaseIntermediateOutputPath)\GX
- Person.Validator.g.cs
// <auto-generated/>
#nullable enable
namespace Valid
{
#pragma warning disable CS0105
using System.ComponentModel.DataAnnotations;
using Validly;
#pragma warning restore CS0105
public partial class Person
: global::Validly.IValidatable, global::Validly.Validators.IInternalValidationInvoker
{
/// <inheritdoc />
ValueTask<global::Validly.ValidationResult> global::Validly.Validators.IInternalValidationInvoker.ValidateAsync(
global::Validly.ValidationContext context,
global::System.IServiceProvider? serviceProvider
)
{
var result = (global::Validly.IInternalValidationResult)global::Validly.ExtendableValidationResult.Create(2);
global::Validly.IExpandablePropertyValidationResult propertyResult;
// Validate "Name" property
context.SetProperty("Name");
propertyResult = result.InitProperty("Name");
propertyResult.Add(PersonRules.NameRule.Item1.IsValid(Name));
return new ValueTask<global::Validly.ValidationResult>((global::Validly.ValidationResult)result);
}
/// <inheritdoc />
async ValueTask<global::Validly.ValidationResult> global::Validly.IValidatable.ValidateAsync(IServiceProvider serviceProvider){
using var validationContext = global::Validly.ValidationContext.Create(this);
return await ((global::Validly.Validators.IInternalValidationInvoker)this).ValidateAsync(validationContext, serviceProvider);
}
/// <summary>
/// Validate the object and get the result with error messages.
/// </summary>
/// <returns>Returns disposable ValidationResult.</returns>
public virtual async ValueTask<global::Validly.ValidationResult> ValidateAsync()
{
using var validationContext = global::Validly.ValidationContext.Create(this);
return await ((global::Validly.Validators.IInternalValidationInvoker)this).ValidateAsync(validationContext, null);
}
/// <summary>
/// Validate the object and get the result with error messages.
/// </summary>
/// <returns>Returns disposable ValidationResult.</returns>
public virtual global::Validly.ValidationResult Validate()
{
using var validationContext = global::Validly.ValidationContext.Create(this);
var task = ((global::Validly.Validators.IInternalValidationInvoker)this).ValidateAsync(validationContext, null);
if (!task.IsCompletedSuccessfully)
{
#if NET7_0_OR_GREATER
throw new global::System.Diagnostics.UnreachableException("The task should be completed synchronously but was not.");
#else
throw new global::System.InvalidOperationException("The task should be completed synchronously but was not.");
#endif
}
return task.Result;
}
}
file static class PersonRules
{
internal static readonly ValueTuple<
global::Validly.Extensions.Validators.Common.RequiredAttribute,
object?
> NameRule = (
new global::Validly.Extensions.Validators.Common.RequiredAttribute(allowEmptyStrings: true),
null
);
}
}
Useful
Download Example (.NET C#)
Share validly
https://ignatandrei.github.io/RSCG_Examples/v2/docs/validly
Category "Validator" has the following generators:
1 validly