Skip to content
Purview Dev logo

Purview.Results.ZodSharp bridges ZodSharp ValidationResult<T> values into results, so validation outcomes flow through the same result pipeline as every other expected outcome instead of throwing.

Terminal window
dotnet add package Purview.Results.ZodSharp

ZodSharp validation never throws: Validate returns a ValidationResult<T> carrying the validated value on success and every ValidationError on failure. That is already a result-shaped value, but it is not Result<TValue, TError> — the failure type is fixed rather than chosen by the caller. ToResult closes that gap.

return RepositoryReconciliationResultSchema
.Validate(reconciliationResult)
.ToResult<RepositoryReconciliationResult, ReconciliationError>(errors =>
new ReconciliationResultInvalid(reconciliationResult, errors)
);

ToResult names both type arguments explicitly — including the error type — because a union case does not carry the union type that contains it:

.ToResult<RepositoryReconciliationResult, ReconciliationError>(...)

When the success type differs from the validated type

Section titled “When the success type differs from the validated type”

If the surrounding method’s success value is not the validated value, produce the failure with the generated AsFailure<TValue>() helper instead, because the validated value cannot be carried forward:

var validated = ProviderConnectionIdSchema.Validate(providerConnectionId);
if (!validated.IsSuccess)
return new ProviderConnectionInvalid(providerConnectionId, validated.Errors)
.AsFailure<RepositoryReconciliationResult>();
return await ReconcileCoreAsync(validated.Value, repositories, cancellationToken);

When the method reports only why an input was rejected, ToUnitResult discards the validated value and returns a unit Result<TError>. It still names the validated value type — a union case does not carry its union — but the success holds the Success marker rather than the value:

Result<TenantError> Validate(TenantInput input) =>
TenantInputSchema
.Validate(input)
.ToUnitResult<TenantInput, TenantError>(errors => new TenantInputInvalid(input, errors));

Use ToResult when the success has to carry the validated value, and ToUnitResult when it does not.

ValidateAsync — on the generated schema, the {Type}SchemaValidator DI adapter, or a [ZodSchema(CustomValidationMethodName = ...)] rule — returns a ValueTask<ValidationResult<T>>. ToResultAsync and ToUnitResultAsync fold that into a result exactly as the synchronous methods fold Validate:

async Task<Result<TenantError>> Validate(TenantInput input, CancellationToken cancellationToken) =>
await TenantInputSchemaValidator
.ValidateAsync(input, cancellationToken)
.ToUnitResultAsync<TenantInput, TenantError>(errors => new TenantInputInvalid(input, errors));

The error type is named explicitly for the same reason as the synchronous forms, and the failure factory runs only when validation failed.

ToResultAsync and ToUnitResultAsync also accept a Task<ValidationResult<T>>, the shape Purview.ZodSharp.Http returns. A client’s request and response validation therefore folds into a result like a local Validate, and a server’s validation problem reads back into the same case:

// Validated before it is sent: an invalid body is never sent, and its errors become the case.
var sent = await http
.PostAsJsonValidatedAsync("/api/tenants", input, validator, AppJsonContext.Default.TenantInput, services)
.ToResultAsync<HttpResponseMessage, TenantError>(errors => new TenantInputInvalid(input, errors));
// Rejected by the server: the problem Purview.ZodSharp.AspNetCore wrote reads back into ZodSharp errors.
if (sent.TryGetValue(out var response) && await response.TryReadZodValidationProblemAsync() is { } problem)
return new TenantInputInvalid(input, problem.ToValidationErrors()).AsFailure<Tenant>();

validator is the generated {Type}SchemaValidator. This package takes no dependency on Purview.ZodSharp.Http; reference it in the client. Both are trim-, Native AOT- and Blazor WebAssembly-safe.

Carrying validation errors in the error value

Section titled “Carrying validation errors in the error value”

IValidationErrorCarrier is implemented by an error value that carries ZodSharp validation errors, so an HTTP layer can turn it into a validation problem without knowing the error type:

public readonly record struct TenantInputInvalid(TenantInput Input, ImmutableArray<ValidationError> Errors)
: IValidationErrorCarrier
{
public ImmutableArray<ValidationError> ValidationErrors => Errors;
}

IValidationErrorCarrier exposes a single ValidationErrors member, preserving each ValidationError’s code, origin, category, path and parameters. The origin is the structured origin a rule owns ("value_object" for a type-level rule, "array" for a collection rule), which is how an HTTP layer can answer a whole family of rules without naming each code.

ZodSharp Problem Details consumes the interface; without it, a host would have to map every validation-carrying error individually.

Member Purpose
ValidationResult<TValue>.ToResult<TValue, TError>(Func<ImmutableArray<ValidationError>, TError> onFailure) Success carries the validated value; failure carries the created error. onFailure runs only when validation failed, so a successful validation allocates no error
ValidationResult<TValue>.ToUnitResult<TValue, TError>(Func<ImmutableArray<ValidationError>, TError> onFailure) The value-discarding counterpart: success is a unit Result<TError>, failure carries the created error
ValueTask<ValidationResult<TValue>>.ToResultAsync<TValue, TError>(Func<ImmutableArray<ValidationError>, TError> onFailure) The asynchronous counterpart, for a schema whose validation awaits
ValueTask<ValidationResult<TValue>>.ToUnitResultAsync<TValue, TError>(Func<ImmutableArray<ValidationError>, TError> onFailure) The value-discarding asynchronous counterpart
Task<ValidationResult<TValue>>.ToResultAsync<TValue, TError>(...) / .ToUnitResultAsync<TValue, TError>(...) The same, for APIs that return a Task - Purview.ZodSharp.Http’s request and response validation
IValidationErrorCarrier Implemented by an error value that carries ZodSharp validation errors

A factory returning a result rather than an error is deliberately not offered: for a lambda returning Result<TValue, TError> the compiler prefers a Func<..., TError> parameter and would silently nest the results. Naming the error type explicitly keeps the intent unambiguous.

Terminal window
dotnet run --project src/src/Examples.Zod

Examples.Zod validates a [ZodSchema] TenantInput and turns the outcome into a Result<Tenant, TenantError>, with the rejection carrying its reported ValidationErrors.