Vali-Validation 1.0.0

There is a newer version of this package available.
See the version list below for details.
dotnet add package Vali-Validation --version 1.0.0
                    
NuGet\Install-Package Vali-Validation -Version 1.0.0
                    
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="Vali-Validation" Version="1.0.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="Vali-Validation" Version="1.0.0" />
                    
Directory.Packages.props
<PackageReference Include="Vali-Validation" />
                    
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 Vali-Validation --version 1.0.0
                    
#r "nuget: Vali-Validation, 1.0.0"
                    
#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 Vali-Validation@1.0.0
                    
#: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=Vali-Validation&version=1.0.0
                    
Install as a Cake Addin
#tool nuget:?package=Vali-Validation&version=1.0.0
                    
Install as a Cake Tool

Vali-Validation – Lightweight Validation Library for .NET

Introduction 🚀

Vali‑Validation is a lightweight and extensible .NET validation library designed as an alternative to FluentValidation. It provides a fluent, expressive API to define validation rules on your models and commands, with built‑in support for:

  • Null / Empty checks
  • String rules (length, prefix/suffix, regex)
  • Numeric & date comparisons
  • Collection rules (empty, count, membership)
  • Custom predicates

Integrates seamlessly via dependency injection, making it ideal for Clean or Onion–style architectures.

Installation 📦

To add Vali-Mediator to your .NET project, install it via NuGet with the following command:

dotnet add package Vali-Validation
  • Targets: NET 7/8/9
  • Dependencies: only Microsoft.Extensions.DependencyInjection.Abstractions

🚀 Quick Start

Inherit from AbstractValidator<T> and use RuleFor(...) to declare rules:

using Vali_Validation.Core.Rules;
using Vali_Validation.Core.Validators;

public class UserDto
{
    public string Name  { get; set; }
    public string Email { get; set; }
    public int    Age   { get; set; }
}

public class UserDtoValidator : AbstractValidator<UserDto>
{
    public UserDtoValidator()
    {
        RuleFor(x => x.Name)
            .NotNull()
            .NotEmpty()
            .MinimumLength(3);

        RuleFor(x => x.Email)
            .NotNull()
            .NotEmpty()
            .Email();

        RuleFor(x => x.Age)
            .GreaterThan(0)
            .NotZero();
    }
}

Register in DI Container

InProgram.cs or Startup.cs:

In Program.cs or Startup.cs:

csharp
using Vali_Validation.Core.Extensions; 

var builder = WebApplication.CreateBuilder(args);

builder.Services
       .AddValidationsFromAssembly(Assembly.GetExecutingAssembly());

var app = builder.Build();

Validate Instances

Inject IValidator<T> and call Validate(...):

public class UserService
{
    private readonly IValidator<UserDto> _validator;

    public UserService(IValidator<UserDto> validator)
    {
        _validator = validator;
    }

    public void CreateUser(UserDto user)
    {
        var result = _validator.Validate(user);
        if (!result.IsValid)
        {
            foreach (var kv in result.Errors)
            {
                Console.WriteLine($"{kv.Key}: {string.Join(", ", kv.Value)}");
            }
            return;
        }
        // Proceed with creation…
    }
}

Key Validation Methods

Method Description
NotNull() Ensures value is not null.
NotEmpty() For strings/collections: not null, not empty (and not whitespace for strings).
Empty() Ensures string is empty or collection has no items.
Email() Must match a standard e‑mail regex pattern.
Url() Must be a valid HTTP/HTTPS URL.
MinimumLength(n) String length ≥ n.
MaximumLength(n) String length ≤ n.
Matches(pattern) Value must match a regular expression.
StartsWith(prefix) String must start with given prefix.
EndsWith(suffix) String must end with given suffix.
MustContain(sub, comp) String must contain sub (with optional StringComparison).
EqualTo(other) Value must equal other.
GreaterThan(x) Numeric/comparable > x.
LessThan(x) Numeric/comparable < x.
Between(min,max) Inclusive range for any IComparable (numbers, dates…).
Positive(), Negative(), NotZero() Numeric comparisons against zero.
FutureDate(), PastDate(), Today() DateTime comparisons relative to now/today.
In(IEnumerable<T>) Value must exist in provided collection.
HasCount(n), NotEmptyCollection() Collection must have exactly n items or at least one.
Must(predicate) Custom boolean predicate rule.
WithMessage(msg) Override the default error message of the most recently added rule.

Error Handling & Result Format

Iterating Errors

var result = validator.Validate(user);
if (!result.IsValid)
{
  foreach (var kv in result.Errors)
  {
    Console.WriteLine($"— {kv.Key}:");
    foreach (var msg in kv.Value)
      Console.WriteLine($"   • {msg}");
  }
}

Console Output Example:

— Name:
• The Name field cannot be empty.
• The Name field must be at least 3 characters long.
— Email:
• The Email field must be a valid email address.

JSON Payload for Web APIs

{
  "Name": [
    "The Name field cannot be empty.",
    "The Name field must be at least 3 characters long."
  ],
  "Email": [
    "The Email field must be a valid email address."
  ]
}

Clients receive a dictionary where each key is a property name and each value is an array of messages.

Example: CQRS + EF Core – Validating a Post Creation Command

This example shows how to wire up and use Vali‑Validation in a typical CQRS + Entity Framework Core scenario.

Define the Command

using MediatR;

public class CreatePostCommand : IRequest<int>
{
    public string    Title       { get; set; }
    public string    Content     { get; set; }
    public DateTime  PublishDate { get; set; }
    public int       AuthorId    { get; set; }
}

Create the Validator

using Vali_Validation.Core.Rules;
using Vali_Validation.Core.Validators;

public class CreatePostCommandValidator : AbstractValidator<CreatePostCommand>
{
    public CreatePostCommandValidator()
    {
        RuleFor(x => x.Title)
            .NotNull().WithMessage("Title is required.")
            .NotEmpty().WithMessage("Title cannot be empty.")
            .MinimumLength(5).WithMessage("Title must be at least 5 characters long.");

        RuleFor(x => x.Content)
            .NotNull().WithMessage("Content is required.")
            .NotEmpty().WithMessage("Content cannot be empty.");

        RuleFor(x => x.PublishDate)
            .GreaterThan(DateTime.UtcNow.AddDays(-1))
            .WithMessage("Publish date cannot be in the past.");

        RuleFor(x => x.AuthorId)
            .GreaterThan(0).WithMessage("AuthorId must be a positive integer.");
    }
}

Implement the EF Core Handler

using MediatR;
using Microsoft.EntityFrameworkCore;

public class CreatePostHandler : IRequestHandler<CreatePostCommand, int>
{
    private readonly BloggingContext _context;

    public CreatePostHandler(BloggingContext context)
    {
        _context = context;
    }

    public async Task<int> Handle(CreatePostCommand request, CancellationToken cancellationToken)
    {
        var post = new Post
        {
            Title       = request.Title,
            Content     = request.Content,
            PublishDate = request.PublishDate,
            AuthorId    = request.AuthorId
        };

        _context.Posts.Add(post);
        await _context.SaveChangesAsync(cancellationToken);
        return post.Id;
    }
}

Register Validation and Pipeline Behavior

using Vali_Validation.Core.Extensions;
using MediatR;
using Microsoft.Extensions.DependencyInjection;

var builder = WebApplication.CreateBuilder(args);

builder.Services
    // EF Core DbContext
    .AddDbContext<BloggingContext>(opts => 
        opts.UseSqlServer(builder.Configuration.GetConnectionString("Default")))

 services.AddMediatR(cfg => 
        {
            // MediatR handlers
            cfg.RegisterServicesFromAssembly(Assembly.GetExecutingAssembly());
           // Add the validation pipeline behavior
            cfg.AddBehavior(typeof(IPipelineBehavior<,>), typeof(ValidationBehavior<,>));
        });

    // Vali‑Validation: automatically register all IValidator<T> in this assembly
    builder.Services.AddValidationsFromAssembly(Assembly.GetExecutingAssembly());

var app = builder.Build();

Usage in Controller or Service

[ApiController]
[Route("api/posts")]
public class PostsController : ControllerBase
{
    private readonly IMediator _mediator;

    public PostsController(IMediator mediator)
    {
        _mediator = mediator;
    }

    [HttpPost]
    public async Task<IActionResult> Create(CreatePostCommand cmd)
    {
        var result = await _mediator.Send(cmd);
        return CreatedAtAction(nameof(GetById), new { id = result }, null);
    }

    // ...
}

If any rule fails, the ValidationBehavior in the pipeline will detect IValidator<CreatePostCommand>, call Validate(cmd), and typically throw a *ValidationException+ or return a 400 with the error dictionary:

{
  "Title": [
    "Title must be at least 5 characters long."
  ],
  "PublishDate": [
    "Publish date cannot be in the past."
  ]
}

With this setup, every CreatePostCommand* is automatically validated—no manual checks in your handlers or controllers.

To have your API automatically return the JSON error payload as shown below, you must register a MediatR ValidationBehavior<TRequest,TResponse> (or equivalent pipeline) that invokes all IValidator<TRequest> instances and throws a ValidationException. You must also add middleware (or exception filter) to catch that exception and write ex.Errors as the HTTP 400 response body.

Features and Enhancements 🌟

Recent Updates

  • Fluent, chainable syntax
  • Rich set of built‑in validators
  • Automatic DI registration (AddValidationsFromAssembly)
  • Lightweight: minimal dependencies
  • Clean / Onion architecture–friendly

🚧 Planned Features

  • Async rules (MustAsync)
  • Error message localization

Follow the project on GitHub for updates on new features and improvements!

Donations 💖

If you find Vali-Validation useful and would like to support its development, consider making a donation:

Your contributions help keep this project alive and improve its development! 🚀

License 📜

This project is licensed under the Apache License 2.0.

Contributions 🤝

Feel free to open issues and submit pull requests to improve this library!

Product Compatible and additional computed target framework versions.
.NET net7.0 is compatible.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  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 was computed.  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 (4)

Showing the top 4 NuGet packages that depend on Vali-Validation:

Package Downloads
Vali-Validation.MediatR

MediatR integration for Vali-Validation. Targets net7.0/net8.0/net9.0/net10.0. Adds a ValidationBehavior<TRequest, TResponse> pipeline behavior that automatically validates IRequest objects using Vali-Validation before they reach their handler. Throws ValidationException on failure. Pinned to MediatR 12.4.1 (the last fully Apache-licensed release) so installing this package never pulls in MediatR's commercial license requirement. Use Vali-Validation.ValiMediator instead if you use Vali-Mediator — it provides richer integration with Result<T> support (no exceptions needed) and stays free.

Vali-Validation.AspNetCore

ASP.NET Core integration for Vali-Validation. Targets net7.0/net8.0/net9.0/net10.0. Provides: - ValiValidationMiddleware: catches ValidationException and returns HTTP 400 problem+json. - ValiValidationFilter<T>: Minimal API endpoint filter for automatic request validation. - ValiValidateAttribute: MVC action filter for automatic controller action validation. - UseValiValidationExceptionHandler() and WithValiValidation<T>() extension methods.

Vali-Validation.ValiMediator

Vali-Mediator integration for Vali-Validation. Targets net7.0/net8.0/net9.0/net10.0. Adds a ValidationBehavior<TRequest, TResponse> that validates IRequest objects before they reach their handler. When TResponse is Result<T>, validation failures are returned as Result.Fail(errors, ErrorType.Validation) — no exceptions needed. For other response types, throws ValidationException. Package name: Vali-Validation.ValiMediator. Requires Vali-Mediator.

Vali-Validation.TestHelpers

Test-assertion helpers for Vali-Validation. Targets net7.0/net8.0/net9.0/net10.0. Adds fluent ShouldHaveValidationErrorFor / ShouldNotHaveValidationErrorFor extensions on ValidationResult. Framework-agnostic — throws ValidationAssertionException on failure, which any test runner (xUnit, NUnit, MSTest) fails the test on as an unhandled exception, without requiring a dependency on that runner from this package.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
3.0.0 238 9/29/2026
2.0.2 243 4/14/2026
2.0.1 283 3/18/2026
2.0.0 232 3/16/2026
1.0.0 319 4/16/2025

Vali-Validation v1.0.0 introduces a lightweight, expressive, and extensible validation framework for .NET developers:
           - Fluent, chainable syntax for defining validation rules with clarity and precision.
           - Built-in support for common scenarios: null checks, empty values, length restrictions, regular expressions, numeric comparisons, date validations, and collection rules.
           - Designed to integrate seamlessly into projects using Onion or Clean Architecture, promoting separation of concerns through validator classes.
           - Compatible with .NET Standard 2.0 and above, ensuring broad framework support.
           - Ideal alternative to FluentValidation, with simpler customization and a focus on maintainability.

           Vali-Validation empowers developers to write clean, testable, and reusable validation logic across applications.