# Valiant validation Documentation version: 1. This context contains only this version. Source revision: 34222bb7277ce1a771ae4412d572b56f5eb98237. ## Validation Source: https://valiant.staticnorth.dev/validation/ # Validation you can step through Valiant Validation generates direct validators from compact, strongly typed rules. Author rules with fluent C#, model attributes, native branches, nested contexts, and reusable validators; then connect them to ASP.NET Core, OpenAPI, MediatR, or source-generated Mediator. ```csharp using StaticNorth.Valiant.Validation; [ValiantValidator] public sealed partial class CreateUserValidator : ValidatorDefinition { public override void Configure(ValidationContext context) { context.Property(user => user.Name) .Required() .MaxLength(64); context.Property(user => user.Age) .GreaterThanOrEqualTo(18); } } ``` ## One rule model, several hosts | Layer | Integration | | --- | --- | | Domain/application | Inject `IValidator` and call sync or async validation APIs | | Minimal APIs | Add `.WithValiantValidation()` to a route | | MVC | Register Valiant model validation globally | | OpenAPI | Project generated rule metadata into schema constraints and `x-valiant-rules` | | Messaging | Add a MediatR or Mediator pipeline behavior | Validation results preserve property paths, codes, messages, and severity. Errors invalidate the result; warnings and information remain available without making it invalid. ## Documentation map - [Quick start](https://valiant.staticnorth.dev/validation/quick-start) - [Runnable samples](https://valiant.staticnorth.dev/validation/samples) - [Authoring rules](https://valiant.staticnorth.dev/validation/guides/authoring-rules) - [Composition and control flow](https://valiant.staticnorth.dev/validation/guides/composition-control-flow) - [ASP.NET Core and OpenAPI](https://valiant.staticnorth.dev/validation/guides/aspnetcore-openapi) - [Mediator pipelines](https://valiant.staticnorth.dev/validation/guides/mediator-pipelines) - [Validation check catalog](https://valiant.staticnorth.dev/validation/reference/validation-checks) - [Runtime and generation](https://valiant.staticnorth.dev/validation/reference/runtime-generation) - [Package guide](https://valiant.staticnorth.dev/validation/reference/packages) The [sample catalog](https://valiant.staticnorth.dev/validation/samples) covers every selectable core and ASP.NET Core scenario. The same behaviors are covered by sample-focused tests, including `WebApplicationFactory` tests for every web sample. ## Quick start Source: https://valiant.staticnorth.dev/validation/quick-start # Quick start ## 1. Install ```bash dotnet add package StaticNorth.Valiant.Validation ``` For an application integration, install the most specific package instead. For example, `StaticNorth.Valiant.Validation.AspNetCore` carries the core runtime, build, and analyzer assets needed to generate validators. ## 2. Declare a validator ```csharp using StaticNorth.Valiant.Validation; public sealed record RegisterUser(string? Name, int Age); [ValiantValidator] public sealed partial class RegisterUserValidator : ValidatorDefinition { public override void Configure(ValidationContext context) { context.Property(request => request.Name) .Required("NameRequired", "Enter a name.") .MaxLength(64); context.Property(request => request.Age) .GreaterThanOrEqualTo(18); } } ``` The declaration must be `partial` and marked with `[ValiantValidator]`. The generator emits `IValidator` directly on the class. ## 3. Validate ```csharp IValidator validator = new RegisterUserValidator(); ValidationResult result = validator.Validate(new RegisterUser(null, 16)); if (!result.IsValid) { foreach (var failure in result.Errors) { Console.WriteLine($"{failure.PropertyName}: {failure.ErrorMessage}"); } } ``` Use `ValidateAsync` for validators that contain async rules. Convenience APIs include `IsValid`, `IsValidAsync`, and `ThrowIfFailed` on the result. ## 4. Register generated validators ```csharp using StaticNorth.Valiant.Validation.DependencyInjection; builder.Services.AddValiantValidators(options => { options.Mode = ValiantValidationMode.Auto; options.FailureBehavior = ValiantFailureBehavior.ValidateAll; options.Lifetime = ValiantValidatorLifetime.Scoped; }); ``` Inject `IValidator` wherever the request is handled. :::tip Async rule safety Call `ValidateAsync` when a validator or reused property validator may perform asynchronous work. The synchronous API does not silently block on async validation. ::: ## ASP.NET Core and OpenAPI Source: https://valiant.staticnorth.dev/validation/guides/aspnetcore-openapi # ASP.NET Core and OpenAPI Install the integrations you use: ```bash dotnet add package StaticNorth.Valiant.Validation.AspNetCore dotnet add package StaticNorth.Valiant.Validation.AspNetCore.OpenApi ``` ## Minimal APIs Register validators and attach validation to a route: ```csharp builder.Services.AddValiantValidators(); app.MapPost("/users", (CreateUser request) => Results.Created()) .WithValiantValidation(); ``` The non-generic overload uses each non-null argument's exact declared parameter type. `[ValiantValidator]` discovery emits the validator, its typed invocation bridge, and their registrations into the generated `AddValiantValidators()` method. The normal path therefore needs no per-model registration or runtime assembly scan. The generated method covers default validators discovered in the current compilation. Arguments with the same declared type reuse the validators resolved for that request while retaining handler-argument execution order. Use the typed overload to resolve `IValidator` and validate every non-null handler argument assignable to `T`: ```csharp app.MapPost("/users", (CreateUser request, CancellationToken cancellationToken) => Results.Created()) .WithValiantValidation(); ``` The generated parameterless path supports Native AOT. Manually registered raw `IValidator` services without a generated bridge remain compatible through a JIT-only fallback. For an explicit manual registration in Native AOT, use the typed overload. MVC does not receive this Native AOT guarantee. Errors return HTTP validation problem details before the handler runs. Warnings and informational failures do not block the handler. ## MVC Register the global model-validation filter directly or through MVC builders: ```csharp builder.Services.AddValiantValidators(); builder.Services.AddValiantMvcValidation(); // Equivalent integration point: builder.Services.AddControllers().AddValiantValidation(); ``` ## Problem details helpers Use `ValiantProblemDetails` when your endpoint or controller validates manually: ```csharp var result = await validator.ValidateAsync(request, cancellationToken); if (!result.IsValid) { return Results.ValidationProblem(result.ToValidationProblemDictionary()); } ``` Helpers are available for Minimal API `HttpValidationProblemDetails`, MVC `ValidationProblemDetails`, and property-to-message dictionaries. ## OpenAPI ```csharp builder.Services.AddOpenApi(); builder.Services.AddValiantOpenApi(); ``` Or attach the transformer to a specific OpenAPI document: ```csharp builder.Services.AddOpenApi(options => options.AddValiantValidationRules()); ``` Valiant projects generated metadata into native constraints where possible—such as required, length, count, and comparison bounds—and preserves richer details in `x-valiant-rules` extensions. :::info Package references Each integration package forwards the core Valiant runtime and generator assets. Add both ASP.NET Core packages when you need request validation and OpenAPI; do not add a redundant direct `StaticNorth.Valiant.Validation` reference. ::: The [Validation sample catalog](https://valiant.staticnorth.dev/validation/samples#aspnet-core-validation) links the Minimal API, MVC, problem-details, and OpenAPI startup implementations. ## Authoring rules Source: https://valiant.staticnorth.dev/validation/guides/authoring-rules # Authoring rules ## Fluent definitions Inherit `ValidatorDefinition` and override `Configure`: ```csharp [ValiantValidator] public sealed partial class ProductValidator : ValidatorDefinition { public override void Configure(ValidationContext context) { context.Property(product => product.Name) .Required() .LengthBetween(3, 80); context.Property(product => product.Price) .GreaterThan(0m); } } ``` The instance method also works naturally with constructor-injected dependencies and reusable validators. ## Attribute definitions Derive from `ValidatorDefinition` to read Valiant validation attributes from the model: ```csharp [ValiantValidator] public sealed partial class ProductValidator : ValidatorDefinition; public sealed class Product { [Required("NameRequired", "Enter a product name.")] [LengthBetween(3, 80)] public string? Name { get; init; } [GreaterThan(0)] public decimal Price { get; init; } } ``` These are attributes from `StaticNorth.Valiant.Validation`, not Data Annotations. Fluent and attribute rules use the same generated checks and metadata. ## Custom predicates Use `Satisfies` for a rule that is clearer as code: ```csharp context.Property(order => order.Reference) .Satisfies( value => value is null || value.StartsWith("ORD-", StringComparison.Ordinal), code: "ReferenceFormat", message: "Reference must start with ORD-."); ``` Async predicate overloads are available for work that accepts a cancellation token. ## Conditions Apply a condition to a property chain: ```csharp context.Property(request => request.InviteCode) .Required() .When(request => request.RequiresInvite); ``` For larger branches, use normal C# control flow. See [Composition and control flow](https://valiant.staticnorth.dev/validation/guides/composition-control-flow). ## Codes, messages, and severity Every built-in check accepts optional `code`, `message`, and `severity` arguments: ```csharp context.Property(user => user.DisplayName) .MaxLength( 40, code: "DisplayNameLong", message: "Display name is longer than 40 characters.", severity: ValiantSeverity.Warning); ``` `ValidationResult.Errors` determine `IsValid`. `Warnings` and `Infos` are preserved separately for callers that want non-blocking feedback. ## Composition and control flow Source: https://valiant.staticnorth.dev/validation/guides/composition-control-flow # Composition and control flow ## Write normal C# branches Validator configuration supports native `if`/`else`, `switch`, loops, and `foreach`: ```csharp public void Configure(ValidationContext context) { if (context.Instance.RequiresApproval) { context.Property(order => order.ApproverId).Required(); } switch (context.Instance.Channel) { case SalesChannel.Store: context.Property(order => order.StoreId).Required(); break; case SalesChannel.Web: context.Property(order => order.SessionId).Required(); break; } } ``` In `Debuggable` mode this method executes at runtime, so ordinary breakpoints and step-through debugging work. ## Nested objects Use `Children` to validate a nested context and retain the complete property path: ```csharp context.Property(order => order.Customer) .Required() .Children(customer => { customer.Property(value => value.Name).Required(); customer.Property(value => value.Email).MaxLength(200); }); ``` ## Collections Use `ForEach` for element rules. `context.Item` is the current item inside the nested validation context: ```csharp context.Property(order => order.Lines) .MinCount(1) .ForEach(line => { line.Property(item => item.Sku).Required(); line.Property(item => item.Quantity).GreaterThan(0); }); ``` Failures include indexed paths such as `Lines[0].Sku`. ## Reuse a root validator ```csharp public sealed partial class CheckoutValidator(AddressValidator addressValidator) : ValidatorDefinition { public override void Configure(ValidationContext context) { context.UseValidator(addressValidator); context.Property(value => value.AcceptedTerms).Equal(true); } } ``` ## Reuse a property validator Create a reusable `PropertyValidatorDefinition` and attach it to a property: ```csharp context.Property(order => order.ShippingAddress) .Required() .UseValidator(addressPropertyValidator); ``` Property validators skip null values. Add `Required()` or `NotNull()` when absence itself is invalid. Attribute-authored models can use `[UseValidator]`. ## Failure behavior Configure collection globally, then override it at validator or property-chain scope: ```csharp services.AddValiantValidators(options => options.FailureBehavior = ValiantFailureBehavior.ValidateAll); ``` Use `FailFast` to stop within the configured scope after the first failure; use `ValidateAll` to collect all applicable failures. Narrower configuration overrides the global option. ## Mediator pipelines Source: https://valiant.staticnorth.dev/validation/guides/mediator-pipelines # Mediator pipelines ## MediatR Install `StaticNorth.Valiant.Validation.MediatR`, register generated validators, and add the behavior through MediatR configuration: ```csharp builder.Services.AddValiantValidators(); builder.Services.AddMediatR(configuration => { configuration.RegisterServicesFromAssemblyContaining(); configuration.AddValiantValidation(); }); ``` The package targets MediatR 12.5.0, the final free MediatR release. ## Source-generated Mediator Install `StaticNorth.Valiant.Validation.Mediator`: ```csharp builder.Services.AddValiantValidators(); builder.Services.AddMediator(options => { options.Assemblies = [typeof(CreateUserCommand).Assembly]; }); builder.Services.AddValiantMediatorValidation(); ``` For Native AOT, list the behavior in the source-generated pipeline: ```csharp builder.Services.AddMediator(options => { options.Assemblies = [typeof(CreateUserCommand).Assembly]; options.PipelineBehaviors = [typeof(ValiantValidationBehavior<,>)]; }); ``` :::warning Choose one Mediator registration path Do not call `AddValiantMediatorValidation()` when `ValiantValidationBehavior<,>` is already present in `PipelineBehaviors`. ::: Both integrations resolve all registered `IValidator` instances, run them before the next handler, and surface validation failure instead of invoking the handler. ## Package guide Source: https://valiant.staticnorth.dev/validation/reference/packages # Package guide Install the most specific package for each integration you use. Integration packages carry the core validation runtime, build, and analyzer assets, so a separate `StaticNorth.Valiant.Validation` reference is unnecessary. | Package | Use it for | Target | | --- | --- | --- | | `StaticNorth.Valiant.Validation` | Core validators without a host integration | .NET 8 and .NET Standard 2.0 | | `StaticNorth.Valiant.Validation.AspNetCore` | Minimal APIs, MVC, and problem details | .NET 8 | | `StaticNorth.Valiant.Validation.AspNetCore.OpenApi` | Native ASP.NET Core OpenAPI schema rules | .NET 10 | | `StaticNorth.Valiant.Validation.MediatR` | MediatR 12.5 pipeline validation | .NET 8 | | `StaticNorth.Valiant.Validation.Mediator` | Source-generated Mediator pipeline validation | .NET 8 | ## Common combinations ```xml ``` ```xml ``` ```xml ``` Reference more than one integration package when the application uses more than one integration. Do not add the core package solely to make source generation work. ## Runtime and generation Source: https://valiant.staticnorth.dev/validation/reference/runtime-generation # Runtime and generation ## Validator API Generated validators implement `IValidator`: ```csharp ValidationResult Validate(T instance); ValueTask ValidateAsync(T instance, CancellationToken cancellationToken = default); bool IsValid(T instance); ValueTask IsValidAsync(T instance, CancellationToken cancellationToken = default); ``` Use async APIs whenever a validator graph can contain async predicates or async property validators. ## Options | Option | Values | Default | | --- | --- | --- | | `Mode` | `Auto`, `Debuggable`, `Fast` | `Auto` | | `FailureBehavior` | `ValidateAll`, `FailFast` | `ValidateAll` | | `Lifetime` | `Scoped`, `Transient`, `Singleton` | `Scoped` | `Auto` uses the runtime, debuggable backend in Debug builds and generated fast code otherwise. `Debuggable` lets you step through `Configure`; `Fast` always uses direct generated checks. Choose validator lifetime based on constructor dependencies. A singleton validator must not capture scoped services. ## Result model `ValidationResult` exposes all failures as well as `Errors`, `Warnings`, and `Infos`. Only error severity makes `IsValid` false. Each `ValidationFailure` includes `PropertyName`, `ErrorCode`, `ErrorMessage`, and `Severity`. Results are immutable and do not need disposal. In `Fast` mode, simple validators with at most six checks and fixed default failure content reuse results after each failure combination is first seen. All checks still run on every call. Reuse is bounded to 63 nonempty combinations per validator type. Custom diagnostic expressions, culture-dependent messages, composition, async checks, and larger validators keep the owned-result path. ## Generator scope `[ValiantValidator]` is the discovery hook. Only marked validator declarations enter the incremental pipeline. Generated output can include: - direct sync/async `IValidator` methods; - metadata used by OpenAPI and integrations; - generated DI registration through `AddValiantValidators`; - composition code for root and property validators. The marker accepts generic and `typeof(...)` compatibility forms. Prefer an ordinary `[ValiantValidator]` declaration that inherits `ValidatorDefinition`; it is the recommended authoring surface for both fluent and attribute-based validation. ## Authoring constraints - Validator and generated containing types must be `partial`. - Attribute rules must be Valiant validation attributes. - Generator-readable expressions produce direct fast-path code; unsupported declaration shapes are compile-time diagnostics rather than runtime surprises. - Property validators skip null property values unless presence is checked separately. ## Validation check catalog Source: https://valiant.staticnorth.dev/validation/reference/validation-checks # Validation check catalog All checks accept optional `code`, `message`, and `severity`. Nullable value checks generally skip `null`; combine them with `Required()` or `NotNull()` when null is invalid. ## General values | Check | Purpose | | --- | --- | | `NotNull()` / `Null()` | Require presence or absence | | `Required()` | Require a non-null value and, for strings/collections, non-empty content | | `NotEmpty()` / `Empty()` | Require content or emptiness | | `Equal(value)` / `NotEqual(value)` | Compare with an expected value | | `Satisfies(predicate)` | Apply a custom sync or async predicate | | `UseValidator(validator)` | Delegate to a reusable property validator | ## Comparable values `GreaterThan`, `GreaterThanOrEqualTo`, `LessThan`, `LessThanOrEqualTo`, `InclusiveBetween`, and `ExclusiveBetween` support compatible comparable values and nullable counterparts. ```csharp context.Property(product => product.Price) .GreaterThan(0m) .LessThanOrEqualTo(10_000m); ``` ## Strings and length-bearing values | Check | Purpose | | --- | --- | | `LengthBetween(min, max)` | Inclusive length range | | `MinLength(min)` | Minimum length | | `MaxLength(max)` | Maximum length | ## Collections | Check | Purpose | | --- | --- | | `Count(count)` | Exact item count | | `CountBetween(min, max)` | Inclusive item-count range | | `MinCount(min)` / `MaxCount(max)` | Count bounds | | `Contains(item)` / `Excludes(item)` | Membership | | `All(predicate)` / `Any(predicate)` / `None(predicate)` | Element predicates | | `ForEach(configure)` | Validate every item with a nested context | ## Dictionaries `HasKey(key)` and `HasValue(value)` validate dictionary membership. ## Enums | Check | Input | | --- | --- | | `DefinedEnum()` | Enum or nullable enum value | | `EnumName(enumType)` | String name | | `EnumValue(enumType)` | Supported integral value or nullable counterpart | ## Attribute equivalents Attribute-authored validators support the corresponding Valiant attributes for declarative checks, including required/nullability, equality, enum, length/count, collection membership, dictionary, and comparison rules. Rules that require executable delegates—custom predicates, native control flow, and inline `ForEach` contexts—belong in a fluent `ValidatorDefinition`. ## Samples Source: https://valiant.staticnorth.dev/validation/samples # Validation samples Validation has separate console and ASP.NET Core sample projects. Each runnable choice owns its description on its `Sample` or `Startup` class; `Program.cs` only selects which one to execute. ## Core validation Run the console project: ```bash dotnet run --project validation/samples/StaticNorth.Valiant.Validation.Samples ``` Select one delegate in [`Program.cs`](https://github.com/static-north-dev/valiant/blob/main/validation/samples/StaticNorth.Valiant.Validation.Samples/Program.cs): | Delegate | Demonstrates | Source | | --- | --- | --- | | `Basic.Sample.RunAsync` | A minimal fluent validator, generated registration, validation, and failure output | [`Basic`](https://github.com/static-north-dev/valiant/tree/main/validation/samples/StaticNorth.Valiant.Validation.Samples/Basic) | | `AttributeValidation.Sample.RunAsync` | Validation attributes on the model with the generated validator contract | [`AttributeValidation`](https://github.com/static-north-dev/valiant/tree/main/validation/samples/StaticNorth.Valiant.Validation.Samples/AttributeValidation) | | `DependencyInjection.Sample.RunAsync` | Generated registrations, configurable lifetime and defaults, concrete non-default validators, property validators, and metadata providers | [`DependencyInjection`](https://github.com/static-north-dev/valiant/tree/main/validation/samples/StaticNorth.Valiant.Validation.Samples/DependencyInjection) | | `SyncAndAsyncValidation.Sample.RunAsync` | Sync and async APIs, boolean helpers, and the guard against synchronously invoking an asynchronous validator | [`SyncAndAsyncValidation`](https://github.com/static-north-dev/valiant/tree/main/validation/samples/StaticNorth.Valiant.Validation.Samples/SyncAndAsyncValidation) | | `Severity.Sample.RunAsync` | Error, warning, and information severities, including valid warning-only and information-only results | [`Severity`](https://github.com/static-north-dev/valiant/tree/main/validation/samples/StaticNorth.Valiant.Validation.Samples/Severity) | | `CompositionAndPaths.Sample.RunAsync` | Whole-model composition, reusable property validators, child contexts, collection items, and nested/indexed paths | [`CompositionAndPaths`](https://github.com/static-north-dev/valiant/tree/main/validation/samples/StaticNorth.Valiant.Validation.Samples/CompositionAndPaths) | | `FailureHandling.Sample.RunAsync` | Per-property fail-fast behavior, result helpers, and `ThrowIfFailed()` | [`FailureHandling`](https://github.com/static-north-dev/valiant/tree/main/validation/samples/StaticNorth.Valiant.Validation.Samples/FailureHandling) | | `ControlFlowAndCollections.Sample.RunAsync` | Collection and dictionary rules, conditions, switches, indexed validation, and native loops | [`ControlFlowAndCollections`](https://github.com/static-north-dev/valiant/tree/main/validation/samples/StaticNorth.Valiant.Validation.Samples/ControlFlowAndCollections) | The [`Catalog`](https://github.com/static-north-dev/valiant/tree/main/validation/samples/StaticNorth.Valiant.Validation.Samples/Catalog) folder is shared support code for the advanced scenarios, not an additional selectable sample. ## ASP.NET Core validation Run the web project: ```bash dotnet run --project validation/samples/StaticNorth.Valiant.Validation.AspNetCore.Samples ``` Select one startup in [`Program.cs`](https://github.com/static-north-dev/valiant/blob/main/validation/samples/StaticNorth.Valiant.Validation.AspNetCore.Samples/Program.cs): | Startup | Demonstrates | Source | | --- | --- | --- | | `MinimalApi.Startup` | Typed and all-parameter Minimal API filters that reject invalid requests before the handler runs | [`MinimalApi`](https://github.com/static-north-dev/valiant/tree/main/validation/samples/StaticNorth.Valiant.Validation.AspNetCore.Samples/MinimalApi) | | `Mvc.Startup` | Automatic MVC validation without a validator dependency or manual validation branch in the controller | [`Mvc`](https://github.com/static-north-dev/valiant/tree/main/validation/samples/StaticNorth.Valiant.Validation.AspNetCore.Samples/Mvc) | | `ProblemDetails.Startup` | Manual validation converted to HTTP and MVC validation problem-details responses | [`ProblemDetails`](https://github.com/static-north-dev/valiant/tree/main/validation/samples/StaticNorth.Valiant.Validation.AspNetCore.Samples/ProblemDetails) | | `OpenApi.Startup` | Generated Valiant validation metadata projected into the application's OpenAPI document | [`OpenApi`](https://github.com/static-north-dev/valiant/tree/main/validation/samples/StaticNorth.Valiant.Validation.AspNetCore.Samples/OpenApi) | The [`Orders`](https://github.com/static-north-dev/valiant/tree/main/validation/samples/StaticNorth.Valiant.Validation.AspNetCore.Samples/Orders) folder contains the shared request models and validator; it is not a startup choice. The web scenarios are also exercised through `WebApplicationFactory`, so the sampled registration and HTTP behavior stay covered by the validation test project. See [ASP.NET Core and OpenAPI](https://valiant.staticnorth.dev/validation/guides/aspnetcore-openapi) for consumer setup.