This also removes the description from the package readme. The desciption of the package is shown on nuget.org in the list view and if no package readme is defined on the detail view of a package version. Since we provide a package readme we do not need the description shown twice.
2.2 KiB
2.2 KiB
Features
- Composable validators: Build validators by inheriting from
Validator<T>and defining rules withRuleForandRuleForEach. - Built-in and custom rules: Use helpers like
NotEmpty,Length,Between, andMatches, or define custom predicates withMust. - Structured validation output: Each failure is returned as a
Problemwith a property path, message, severity, code, and attempted value. - Nested validation: Reuse validators for complex object graphs with
SetValidator, including DI-based resolution.
Getting Started
Install the NuGet package:
dotnet add package Geekeey.Request.Validation
You may need to add our NuGet feed to your nuget.config this can be done by running the following command:
dotnet nuget add source -n geekeey https://code.geekeey.de/api/packages/geekeey/nuget/index.json
Usage
using Geekeey.Request.Validation;
public sealed record Address(string? Street);
public sealed record CreateUserRequest(
string? Name,
int Age,
Address? Address,
IReadOnlyList<string> Tags);
public sealed class AddressValidator : Validator<Address>
{
public AddressValidator()
{
RuleFor(address => address.Street)
.NotEmpty();
}
}
public sealed class CreateUserRequestValidator : Validator<CreateUserRequest>
{
public CreateUserRequestValidator()
{
RuleFor(request => request.Name)
.NotEmpty()
.Length(2, 100)
.WithCode("NAME_INVALID");
RuleFor(request => request.Age)
.Between(18, 120);
RuleFor(request => request.Address)
.SetValidator(new AddressValidator());
RuleForEach(request => request.Tags)
.NotEmpty()
.WithSeverity(Severity.Warning);
}
}
var validator = new CreateUserRequestValidator();
var validation = validator.Validate(new CreateUserRequest(
Name: "",
Age: 16,
Address: new Address(""),
Tags: ["", "admin"]));
foreach (var problem in validation.Problems)
{
Console.WriteLine($"{problem.PropertyPath}: {problem.Message}");
}
The resulting Problem entries include full property paths like Address.Street and Tags[0], making it easy to
surface validation errors back to callers or APIs.