Pitasoft.Validation
5.0.1
See the version list below for details.
dotnet add package Pitasoft.Validation --version 5.0.1
NuGet\Install-Package Pitasoft.Validation -Version 5.0.1
<PackageReference Include="Pitasoft.Validation" Version="5.0.1" />
<PackageVersion Include="Pitasoft.Validation" Version="5.0.1" />
<PackageReference Include="Pitasoft.Validation" />
paket add Pitasoft.Validation --version 5.0.1
#r "nuget: Pitasoft.Validation, 5.0.1"
#:package Pitasoft.Validation@5.0.1
#addin nuget:?package=Pitasoft.Validation&version=5.0.1
#tool nuget:?package=Pitasoft.Validation&version=5.0.1
Pitasoft.Validation
A flexible and high-performance C# validation library designed to validate objects using multiple strategies, including Data Annotations, custom rules, and a fluent API.
English
Features
- Multiple Validation Strategies:
- Data Annotations: Leverage existing
System.ComponentModel.DataAnnotationsattributes. - Fluent API: Define validation rules using a clean, readable syntax.
- Custom Rules: Implement complex validation logic via delegates.
- Data Annotations: Leverage existing
- Hierarchical Validation: Support for child validators to validate nested object graphs.
- High Performance: Optimized using expression compilation and caching for property access and display names.
- Pitasoft.Error Integration: Returns errors in the standard
ErrorCollectionformat from thePitasoft.Errorlibrary. - Strongly Typed: Full support for generics and lambda expressions to avoid magic strings.
- Backward Compatibility: Maintains support for legacy
object-based APIs and obsolete methods.
Installation
Add the Pitasoft.Validation package to your project:
dotnet add package Pitasoft.Validation
Note: Depends on Pitasoft.Error.
Target Frameworks
- .NET 10 (
net10.0) - .NET 9 (
net9.0) - .NET 8 (
net8.0)
Quick API Reference
- Validator extensions:
IsValid(instance)→ returnsboolTryValidate(instance, out errors)→ returnsbooland outputsErrorCollectionValidateProperty(instance, x => x.Prop)→ returnsErrorCollectionfor a single property
- Rule collection extensions:
AddRule(x => x.Name, "Name is required", u => !string.IsNullOrWhiteSpace(u.Name))AddRule("Name", "Name is required", u => !string.IsNullOrWhiteSpace(u.Name))AddRules(rule1, rule2, ...)
- Fluent builder examples:
validator.For(x => x.Name).NotNullOrEmpty("Name is required").MaxLength(50, "Too long")validator.For(x => x.Age).Must(u => u.Age >= 18, "Must be 18+")
What's New
- Fluent API with
For(...).Must/NotNullOrEmpty/MaxLengthfor concise rule definitions. - Child validators via
RegisterChildValidatorto validate nested objects and compose errors as paths. - Enriched checker support (
ICheckerRich) to return structured errors.
Getting Started
1. Data Annotations Validation
The simplest way to start is using existing attributes on your models.
public class User
{
[Required]
[StringLength(50)]
public string Name { get; set; }
[Range(18, 99)]
public int Age { get; set; }
}
// Usage with Extension Methods (easiest)
var user = new User { Name = "", Age = 10 };
ErrorCollection errors = user.ValidateWithAttributes();
// Or using a manual validator
var validator = new Validator<User>(new ValidationAttributeChecker<User>());
errors = validator.ValidateObject(user);
if (!errors.Any())
{
// Valid
}
2. Fluent API Rules
Define rules programmatically without modifying your model classes.
// Usage with Extension Methods
var result = user.ValidateWithValidator(v =>
{
v.For(u => u.Name)
.NotNullOrEmpty("Name is required")
.MaxLength(50, "Name is too long");
v.For(u => u.Age)
.Must(age => age >= 18, "Must be at least 18 years old");
});
// Or using a manual validator
var validator = new Validator<User>();
validator.For(u => u.Name).NotNullOrEmpty("Required");
result = validator.ValidateObject(user);
3. Nested Objects (Child Validators)
Validate complex object graphs by registering validators for child properties.
public class Order
{
public Address ShippingAddress { get; set; }
}
var addressValidator = new Validator<Address>(new ValidationAttributeChecker<Address>());
var orderValidator = new Validator<Order>();
// Registering child validator
orderValidator.RegisterChildValidator(o => o.ShippingAddress, addressValidator);
var errors = orderValidator.ValidateObject(order);
// Errors for address will have keys like "ShippingAddress.City"
4. Integration with Pitasoft.Error
All validation results are returned as an ErrorCollection, allowing for easy aggregation and consistent error handling across your application.
public void ProcessUser(User user)
{
var validator = CreateUserValidator();
if (!validator.TryValidate(user, out var errors))
{
// Handle errors (e.g., return HTTP 400 with the collection)
throw new ValidationException(errors);
}
}
Advanced Concepts
IChecker
Implement custom checkers to extend the validation engine. An IChecker can return structured errors with relative paths. This is useful for complex types or when you need to integrate with external validation libraries.
Cross-property validation
The fluent API allows you to access the entire object instance within the Must method, enabling validation that depends on multiple properties:
validator.For(u => u.Age)
.Range(18, 99, "Age for {0} must be between {1} and {2}");
validator.For(u => u.YearsOfExperience)
.Must(u => u.YearsOfExperience >= u.MinRequiredExperience,
"Years of experience for {0} must be at least {1} (minimum required)");
Performance
Validator<T> is designed for high performance:
- Compiled expressions for fast property access.
- Cached display name lookups (from
DisplayAttribute). - Efficient rule grouping and property-based validation.
Español
Características
- Múltiples estrategias de validación:
- Data Annotations: Aprovecha los atributos de
System.ComponentModel.DataAnnotationsexistentes. - API fluida: Define reglas con una sintaxis clara y legible.
- Reglas personalizadas: Implementa lógica compleja mediante delegados.
- Data Annotations: Aprovecha los atributos de
- Validación jerárquica: Soporta validadores hijos para validar grafos de objetos anidados.
- Alto rendimiento: Optimizado con compilación de expresiones y cachés para acceso a propiedades y nombres visibles.
- Integración con Pitasoft.Error: Devuelve errores en el formato estándar
ErrorCollectionde la libreríaPitasoft.Error. - Tipado fuerte: Soporta genéricos y expresiones lambda para evitar "magic strings".
Instalación
Agrega el paquete Pitasoft.Validation a tu proyecto:
dotnet add package Pitasoft.Validation
Nota: Depende de Pitasoft.Error.
Frameworks de destino
- .NET 10 (
net10.0) - .NET 9 (
net9.0) - .NET 8 (
net8.0)
Referencia rápida de API
- Extensiones de validador:
IsValid(instancia)→ devuelveboolTryValidate(instancia, out errores)→ devuelvebooly sacaErrorCollectionValidateProperty(instancia, x => x.Prop)→ devuelveErrorCollectionpara una propiedad
- Extensiones de colección de reglas:
AddRule(x => x.Name, "El nombre es obligatorio", u => !string.IsNullOrWhiteSpace(u.Name))AddRule("Name", "El nombre es obligatorio", u => !string.IsNullOrWhiteSpace(u.Name))AddRules(regla1, regla2, ...)
- Ejemplos con el builder fluido:
validator.For(x => x.Name).NotNullOrEmpty("El nombre es obligatorio").MaxLength(50, "Demasiado largo")validator.For(x => x.Age).Must(u => u.Age >= 18, "Debe ser mayor de 18")
Novedades
- API fluida con
For(...).Must/NotNullOrEmpty/MaxLengthpara definir reglas de forma concisa. - Validadores hijos con
RegisterChildValidatorpara validar objetos anidados y componer rutas de error. - Soporte de errores enriquecidos (
ICheckerRich) para devolver errores estructurados.
Primeros pasos
1. Validación con Data Annotations
La forma más simple de empezar es usando los atributos ya presentes en tus modelos.
public class User
{
[Required]
[StringLength(50)]
public string Name { get; set; }
[Range(18, 99)]
public int Age { get; set; }
}
// Uso con Métodos de Extensión (lo más fácil)
var user = new User { Name = "", Age = 10 };
ErrorCollection errors = user.ValidateWithAttributes();
// O usando un validador manual
var validator = new Validator<User>(new ValidationAttributeChecker<User>());
errors = validator.ValidateObject(user);
if (!errors.Any())
{
// Válido
}
2. Reglas con API fluida
Define reglas programáticamente sin modificar tus clases de modelo.
// Uso con Métodos de Extensión
var result = user.ValidateWithValidator(v =>
{
v.For(u => u.Name)
.NotNullOrEmpty("El nombre es obligatorio")
.MaxLength(50, "El nombre es demasiado largo");
v.For(u => u.Age)
.Range(18, 99, "Debe tener entre 18 y 99 años");
});
// O usando un validador manual
var validator = new Validator<User>();
validator.For(u => u.Name).NotNullOrEmpty("Obligatorio");
result = validator.ValidateObject(user);
3. Objetos anidados (validadores hijos)
Valida grafos complejos registrando validadores para propiedades hijas.
public class Order
{
public Address ShippingAddress { get; set; }
}
var addressValidator = new Validator<Address>(new ValidationAttributeChecker<Address>());
var orderValidator = new Validator<Order>();
// Registrando validador hijo
orderValidator.RegisterChildValidator(o => o.ShippingAddress, addressValidator);
var errors = orderValidator.ValidateObject(order);
// Los errores del address tendrán claves como "ShippingAddress.City"
4. Integración con Pitasoft.Error
Todos los resultados se devuelven como ErrorCollection, lo que permite una agregación sencilla y un manejo de errores consistente en tu aplicación.
public void ProcessUser(User user)
{
var validator = CreateUserValidator();
if (!validator.TryValidate(user, out var errors))
{
// Manejar errores (p.ej., devolver HTTP 400 con la colección)
throw new ValidationException(errors);
}
}
Conceptos avanzados
IChecker
Implementa validadores propios (IChecker) para extender el motor de validación. Un IChecker puede devolver errores estructurados con rutas relativas, ideal para integraciones o tipos complejos.
Validación cruzada entre propiedades
La API fluida permite acceder a la instancia completa del objeto dentro del método Must, facilitando validaciones que dependan de múltiples campos:
validator.For(u => u.YearsOfExperience)
.Must(u => u.YearsOfExperience >= u.MinRequiredExperience,
"Los años de experiencia para {0} deben ser al menos {1} (mínimo requerido)");
Rendimiento
Validator<T> está diseñado para alto rendimiento:
- Expresiones compiladas para un acceso rápido a propiedades.
- Caché de nombres visibles (desde
DisplayAttribute). - Agrupación eficiente de reglas y validación basada en propiedades.
Autor
Sebastián Martínez Pérez
Licencia
Copyright © 2020-2026 Pitasoft, S.L. Distribuido bajo la licencia LICENSE.txt incluida en este repositorio.
| Product | Versions Compatible and additional computed target framework versions. |
|---|---|
| .NET | net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 is compatible. net9.0-android was computed. net9.0-browser was computed. net9.0-ios was computed. net9.0-maccatalyst was computed. net9.0-macos was computed. net9.0-tvos was computed. net9.0-windows was computed. net10.0 is compatible. net10.0-android was computed. net10.0-browser was computed. net10.0-ios was computed. net10.0-maccatalyst was computed. net10.0-macos was computed. net10.0-tvos was computed. net10.0-windows was computed. |
-
net10.0
- Pitasoft.Error (>= 5.3.1)
-
net8.0
- Pitasoft.Error (>= 5.3.1)
-
net9.0
- Pitasoft.Error (>= 5.3.1)
NuGet packages (4)
Showing the top 4 NuGet packages that depend on Pitasoft.Validation:
| Package | Downloads |
|---|---|
|
Pitasoft.Validation.Rules
Implement rules to validate objects |
|
|
Pitasoft.FluentValidation
Provides integration with FluentValidation for Pitasoft.Validation |
|
|
Pitasoft.Validation.AspNetCore
ASP.NET Core integration for Pitasoft.Validation. Provides Minimal API endpoint filters and MVC action filters to validate request parameters using IValidator<T>, IValidatorAsync<T>, IChecker<T>, and ICheckerAsync<T>. |
|
|
Pitasoft.Validation.DependencyInjectionExtensions
Microsoft.Extensions.DependencyInjection integration for Pitasoft.Validation. Provides extension methods to register IValidator<T> and IValidatorAsync<T> implementations into an IServiceCollection, both manually and via assembly scanning. |
GitHub repositories
This package is not used by any popular GitHub repositories.
| Version | Downloads | Last Updated |
|---|---|---|
| 6.0.5 | 253 | 4/1/2026 |
| 6.0.4 | 197 | 3/31/2026 |
| 6.0.3 | 126 | 3/25/2026 |
| 6.0.2 | 120 | 3/25/2026 |
| 6.0.1 | 128 | 3/23/2026 |
| 5.1.5 | 129 | 3/17/2026 |
| 5.1.4 | 129 | 3/17/2026 |
| 5.1.3 | 156 | 3/5/2026 |
| 5.1.2 | 140 | 3/2/2026 |
| 5.1.1 | 132 | 3/2/2026 |
| 5.0.1 | 132 | 2/25/2026 |
| 4.3.0 | 502 | 11/20/2023 |
| 4.2.0 | 315 | 10/23/2023 |
| 4.1.0 | 774 | 11/18/2022 |
| 4.0.2 | 985 | 7/26/2022 |
| 4.0.0 | 841 | 7/26/2022 |
| 3.0.0 | 640 | 7/22/2022 |
| 2.0.0 | 682 | 6/26/2021 |
| 0.0.1 | 132 | 3/23/2026 |