Pitasoft.FluentValidation 2.0.2

dotnet add package Pitasoft.FluentValidation --version 2.0.2
                    
NuGet\Install-Package Pitasoft.FluentValidation -Version 2.0.2
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="Pitasoft.FluentValidation" Version="2.0.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Pitasoft.FluentValidation" Version="2.0.2" />
                    
Directory.Packages.props
<PackageReference Include="Pitasoft.FluentValidation" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add Pitasoft.FluentValidation --version 2.0.2
                    
#r "nuget: Pitasoft.FluentValidation, 2.0.2"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package Pitasoft.FluentValidation@2.0.2
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=Pitasoft.FluentValidation&version=2.0.2
                    
Install as a Cake Addin
#tool nuget:?package=Pitasoft.FluentValidation&version=2.0.2
                    
Install as a Cake Tool

Pitasoft.FluentValidation

NuGet version NuGet downloads Build Status License: MIT .NET Versions FluentValidation Pitasoft.Validation

English | Castellano


English

FluentValidation integration for the Pitasoft.Validation ecosystem.

This package allows using validators created with FluentValidation within the Pitasoft validation system, as well as providing extension methods for direct object validation.

Installation

dotnet add package Pitasoft.FluentValidation

Features

  • Transparent integration with Pitasoft.Validation.
  • Register FluentValidation validators in Pitasoft's Validator<T> (synchronous) and ValidatorAsync<T> (asynchronous).
  • Extension methods for direct synchronous and asynchronous object validation.
  • Async rule support: MustAsync, WhenAsync, etc. via FluentValidationCheckerAsync<T>.
  • Support for multiple .NET versions (net8.0, net9.0, net10.0).

Supported frameworks

  • .NET 8
  • .NET 9
  • .NET 10

Dependency model

Pitasoft.Validation and Pitasoft.Error are installed transitively through the package dependency graph.

Public building blocks

Type Role
FluentValidationChecker<T> Synchronous adapter from FluentValidation to Pitasoft.Validation
FluentValidationCheckerAsync<T> Async-capable adapter from FluentValidation to Pitasoft.Validation
RegisterFluentValidator(...) for Validator<T> Registers a sync checker
RegisterFluentValidator(...) for ValidatorAsync<T> Registers an async-capable checker
ValidateWithFluent(...) Direct synchronous object validation
TryValidateWithFluent(...) Direct synchronous validation with non-null error output
ValidateWithFluentAsync(...) Direct asynchronous object validation

Validation semantics

  • FluentValidation failures are mapped into ErrorCollection.
  • Property paths are preserved as reported by FluentValidation. Examples: Name, Address.City, Items[0].Name.
  • ValidateWithFluent(...) and ValidateWithFluentAsync(...) return null when the instance is null or no errors are found.
  • TryValidateWithFluent(...) always returns a non-null ErrorCollection.
  • Use ValidatorAsync<T> or ValidateWithFluentAsync(...) when FluentValidation rules include async operations.

Usage

Registering in a Pitasoft Validator (synchronous)

Use this option only with synchronous FluentValidation rules. If your validator contains async rules such as MustAsync or WhenAsync, use ValidatorAsync<T> instead.

using Pitasoft.Validation;
using Pitasoft.FluentValidation.Extensions;
using FluentValidation;

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

public class PersonFluentValidator : AbstractValidator<Person>
{
    public PersonFluentValidator()
    {
        RuleFor(x => x.Name).NotEmpty().WithMessage("Name is required.");
        RuleFor(x => x.Age).GreaterThan(0).WithMessage("Age must be greater than 0.");
    }
}

// ... in your business code ...
var validator = new Validator<Person>();
validator.RegisterFluentValidator(new PersonFluentValidator());

var person = new Person { Name = "", Age = 0 };
var errors = validator.ValidateObject(person);

if (errors != null)
{
    foreach (var error in errors)
    {
        Console.WriteLine($"{error.Key}: {string.Join(", ", error.Value)}");
    }
}

If async rules are executed through the synchronous checker, the library throws AsyncRuleInSyncValidationException.

Registering in a Pitasoft Async Validator

Use ValidatorAsync<T> when your FluentValidation rules include async rules (MustAsync, WhenAsync, etc.):

using Pitasoft.Validation;
using Pitasoft.FluentValidation.Extensions;
using FluentValidation;

public class PersonAsyncValidator : AbstractValidator<Person>
{
    public PersonAsyncValidator()
    {
        RuleFor(x => x.Name).MustAsync(async (name, ct) =>
        {
            // e.g., check uniqueness in a database
            await Task.Delay(1, ct);
            return !string.IsNullOrEmpty(name);
        }).WithMessage("Name is required.");

        RuleFor(x => x.Age).GreaterThan(0).WithMessage("Age must be greater than 0.");
    }
}

var validator = new ValidatorAsync<Person>();
validator.RegisterFluentValidator(new PersonAsyncValidator());

var errors = await validator.ValidateObjectAsync(new Person { Name = "", Age = 0 });
Direct Object Validation

Extension methods for quick one-off validation without building a Validator<T>:

using Pitasoft.FluentValidation.Extensions;

var person = new Person { Name = "", Age = 0 };
var fluentValidator = new PersonFluentValidator();

// Synchronous — returns null if valid
var errors = person.ValidateWithFluent(fluentValidator);

// TryParse style
if (!person.TryValidateWithFluent(fluentValidator, out var errorCollection))
{
    // Handle errors...
}

// Asynchronous (supports MustAsync, WhenAsync, etc.)
var asyncErrors = await person.ValidateWithFluentAsync(new PersonAsyncValidator());

As with validator registration, ValidateWithFluent(...) is intended for synchronous FluentValidation rules. Use ValidateWithFluentAsync(...) for validators with async rules.

Author

Sebastián Martínez Pérez

License

Copyright © 2026 Pitasoft, S.L. Distributed under the license included in LICENSE.txt.


Castellano

Integración de FluentValidation para el ecosistema de validación de Pitasoft.Validation.

Este paquete permite utilizar validadores creados con FluentValidation dentro del sistema de validación de Pitasoft, así como proporcionar métodos de extensión para validar objetos de forma directa.

Instalación

dotnet add package Pitasoft.FluentValidation

Características

  • Integración transparente con Pitasoft.Validation.
  • Registro de validadores de FluentValidation en el Validator<T> de Pitasoft (síncrono) y ValidatorAsync<T> (asíncrono).
  • Métodos de extensión para validación directa de objetos, tanto síncrona como asíncrona.
  • Soporte para reglas asíncronas: MustAsync, WhenAsync, etc. mediante FluentValidationCheckerAsync<T>.
  • Soporte para múltiples versiones de .NET (net8.0, net9.0, net10.0).

Frameworks soportados

  • .NET 8
  • .NET 9
  • .NET 10

Modelo de dependencias

Pitasoft.Validation y Pitasoft.Error se instalan de forma transitiva a través de las dependencias del paquete.

Bloques públicos principales

Tipo Rol
FluentValidationChecker<T> Adaptador síncrono de FluentValidation hacia Pitasoft.Validation
FluentValidationCheckerAsync<T> Adaptador con soporte asíncrono hacia Pitasoft.Validation
RegisterFluentValidator(...) para Validator<T> Registra un checker síncrono
RegisterFluentValidator(...) para ValidatorAsync<T> Registra un checker con soporte asíncrono
ValidateWithFluent(...) Validación directa síncrona de objetos
TryValidateWithFluent(...) Validación directa síncrona con salida de errores no nula
ValidateWithFluentAsync(...) Validación directa asíncrona de objetos

Semántica de validación

  • Los errores de FluentValidation se transforman en ErrorCollection.
  • Las rutas de propiedad se conservan tal y como las informa FluentValidation. Ejemplos: Name, Address.City, Items[0].Name.
  • ValidateWithFluent(...) y ValidateWithFluentAsync(...) devuelven null cuando la instancia es null o no hay errores.
  • TryValidateWithFluent(...) siempre devuelve un ErrorCollection no nulo.
  • Usa ValidatorAsync<T> o ValidateWithFluentAsync(...) cuando el validador de FluentValidation incluya operaciones asíncronas.

Uso

Registro en un Validador de Pitasoft (síncrono)

Usa esta opción solo con reglas síncronas de FluentValidation. Si tu validador contiene reglas asíncronas como MustAsync o WhenAsync, utiliza ValidatorAsync<T>.

using Pitasoft.Validation;
using Pitasoft.FluentValidation.Extensions;
using FluentValidation;

public class Persona
{
    public string Nombre { get; set; }
    public int Edad { get; set; }
}

public class PersonaFluentValidator : AbstractValidator<Persona>
{
    public PersonaFluentValidator()
    {
        RuleFor(x => x.Nombre).NotEmpty().WithMessage("El nombre es obligatorio.");
        RuleFor(x => x.Edad).GreaterThan(0).WithMessage("La edad debe ser mayor que 0.");
    }
}

// ... en tu código de negocio ...
var validator = new Validator<Persona>();
validator.RegisterFluentValidator(new PersonaFluentValidator());

var persona = new Persona { Nombre = "", Edad = 0 };
var errors = validator.ValidateObject(persona);

if (errors != null)
{
    foreach (var error in errors)
    {
        Console.WriteLine($"{error.Key}: {string.Join(", ", error.Value)}");
    }
}

Si se ejecutan reglas asíncronas a través del checker síncrono, la librería lanza AsyncRuleInSyncValidationException.

Registro en un Validador Asíncrono de Pitasoft

Usa ValidatorAsync<T> cuando tu validador de FluentValidation contiene reglas asíncronas (MustAsync, WhenAsync, etc.):

using Pitasoft.Validation;
using Pitasoft.FluentValidation.Extensions;
using FluentValidation;

public class PersonaAsyncValidator : AbstractValidator<Persona>
{
    public PersonaAsyncValidator()
    {
        RuleFor(x => x.Nombre).MustAsync(async (nombre, ct) =>
        {
            // p. ej., comprobar unicidad en base de datos
            await Task.Delay(1, ct);
            return !string.IsNullOrEmpty(nombre);
        }).WithMessage("El nombre es obligatorio.");

        RuleFor(x => x.Edad).GreaterThan(0).WithMessage("La edad debe ser mayor que 0.");
    }
}

var validator = new ValidatorAsync<Persona>();
validator.RegisterFluentValidator(new PersonaAsyncValidator());

var errors = await validator.ValidateObjectAsync(new Persona { Nombre = "", Edad = 0 });
Validación Directa de Objetos

Métodos de extensión para validaciones puntuales sin necesidad de construir un Validator<T>:

using Pitasoft.FluentValidation.Extensions;

var persona = new Persona { Nombre = "", Edad = 0 };
var fluentValidator = new PersonaFluentValidator();

// Síncrono — devuelve null si es válido
var errors = persona.ValidateWithFluent(fluentValidator);

// Estilo TryParse
if (!persona.TryValidateWithFluent(fluentValidator, out var errorCollection))
{
    // Manejar errores...
}

// Asíncrono (soporta MustAsync, WhenAsync, etc.)
var asyncErrors = await persona.ValidateWithFluentAsync(new PersonaAsyncValidator());

Igual que en el registro de validadores, ValidateWithFluent(...) está pensado para reglas síncronas de FluentValidation. Para validadores con reglas asíncronas, usa ValidateWithFluentAsync(...).


Autor

Sebastián Martínez Pérez

Licencia

Copyright © 2026 Pitasoft, S.L. Distribuido bajo la licencia incluida en LICENSE.txt.

Product 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. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (1)

Showing the top 1 NuGet packages that depend on Pitasoft.FluentValidation:

Package Downloads
Pitasoft.FluentValidation.AspNetCore

ASP.NET Core integration for FluentValidation. Provides Minimal API endpoint filters and MVC action filters to validate request parameters using FluentValidation.IValidator<T> and returns Pitasoft.Result validation responses.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
2.0.2 174 4/1/2026
2.0.1 121 3/5/2026
1.0.0 262 4/11/2024