ZodSharp
Prerelease. These pages describe 3.0.0-prerelease.2 and can differ from the published release. Read the Live 2.4.2 documentation instead.
Getting Started
Section titled “Getting Started”Install
Section titled “Install”The packages target net10.0 and net11.0 (the .NET 11 integrations target net11.0 only). Applications on
net8.0 or net9.0 stay on the 2.4.x line.
dotnet add package Purview.ZodSharpAdd the integration packages you need:
# System.Text.Json integration + JSON Schema importdotnet add package Purview.ZodSharp.SystemTextJson
# Newtonsoft.Json integration + JSON Schema importdotnet add package Purview.ZodSharp.NewtonsoftJson
# ASP.NET Core ProblemDetails integrationdotnet add package Purview.ZodSharp.AspNetCorePurview.ZodSharp— core library, source generator, and JSON Schema export.Purview.ZodSharp.SystemTextJson— System.Text.Json deserialize-and-validate, validating converters, and JSON Schema import.Purview.ZodSharp.NewtonsoftJson— Newtonsoft.Json deserialize-and-validate, validating converters, and JSON Schema import.Purview.ZodSharp.AspNetCore— failed validation results converted to standardProblemDetails/HttpValidationProblemDetailspayloads.
First schema
Section titled “First schema”using ZodSharp;
var nameSchema = Z.String().Min(3).Max(50);var result = nameSchema.Validate("John");
if (result.IsSuccess) Console.WriteLine($"Valid name: {result.Value}");Validate, SafeParse, and Parse
Section titled “Validate, SafeParse, and Parse”Validatereturns aValidationResult<T>— no exceptions.SafeParseis an alias ofValidate.ParsethrowsZodExceptionon failure.
var value = nameSchema.Parse("AB"); // throws ZodException
var result = nameSchema.SafeParse("AB"); // non-throwingif (!result.IsSuccess){ foreach (var error in result.Errors) Console.WriteLine($" - {error.FullPath.ToDottedString()}: {error.Message}");}Object validation
Section titled “Object validation”var userSchema = Z.Object() .Field("name", Z.String().Min(1)) .Field("age", Z.Number().Min(0).Max(120).Int()) .Field("email", Z.String().Email()) .Build();
var userData = new Dictionary<string, object?>{ { "name", "John Doe" }, { "age", 30.0 },};
var result = userSchema.Validate(userData);Source-generated validators
Section titled “Source-generated validators”Mark a class, struct, or record with [ZodSchema] and a zero-allocation static validator is generated at compile time:
using System.ComponentModel.DataAnnotations;using ZodSharp;
[ZodSchema]public class User{ [Required] [StringLength(50, MinimumLength = 3)] public string Name { get; set; } = string.Empty;
[Range(0, 120)] public int Age { get; set; }
[EmailAddress] public string? Email { get; set; }}
var result = UserSchema.Validate(user);var validated = UserSchema.Parse(user); // throws on failureSee the Source Generator and Source Generator DataAnnotations pages for the full feature set.
JSON integration
Section titled “JSON integration”// System.Text.Json or Newtonsoft.Jsonvar json = """{ "name": "John", "age": 30 }""";var result = userSchema.DeserializeAndValidate(json);// JSON Schema export (core)var jsonSchema = Z.ToJsonSchema(userSchema, new ToJsonSchemaOptions { Title = "User" });
// JSON Schema import (requires an integration package)// using ZodSharp.JsonSchema.SystemTextJson; // or ZodSharp.JsonSchema.NewtonsoftJsonvar imported = Z.FromJsonSchema(jsonSchemaString);See System.Text.Json Integration, Newtonsoft.Json Integration, JSON Schema Export, and JSON Schema Import.
Where to go next
Section titled “Where to go next”This page is the entry point of the wiki, so the rest of it is grouped by what you are trying to do. Each group below is a section of the sidebar, in reading order; Home lists every page in all seven sections.
- Learn the model — Core Concepts explains the pipeline, the result and the error model; Fluent Schema API is the surface every schema type shares.
- Pick a schema or a rule — Validation Rules Reference lists every built-in rule, and each schema type has its own page: String Validation, Number Validation, Object Validation, Arrays and Other Schemas, Unions and Discriminated Unions, Composition and Transforms. Write your own in Custom Rules.
- Generate validators — Source Generator, then Source Generator DataAnnotations, with Source Generator Diagnostics for the codes the build reports.
- Move data across a boundary — JSON Schema Export and JSON Schema Import for interoperability, System.Text.Json Integration and Newtonsoft.Json Integration for deserialize-and-validate.
- Host it — ASP.NET Core Integration, Blazor Integration, HttpClient Integration, Dependency Injection, and Localization for messages. On .NET 11, Microsoft.Extensions.Validation and OpenAPI Integration cover the platform pipeline.
- Ship it — Guarantees and Limitations states what is promised, Performance what it costs, and Trimming and Native AOT what the publish gates check. Cross-Platform Interop covers the Zod parity fixtures.
- Work on it — Contributing and Release Flow.