gozod

package module
v0.11.8 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 13, 2026 License: MIT Imports: 8 Imported by: 1

README

GoZod

Go Module License

A TypeScript Zod v4-inspired validation library for Go with strict type semantics, fluent schemas, struct tags, and JSON Schema Draft 2020-12 interoperability

Features

  • Strict type semantics: Value schemas and pointer schemas accept exact input types unless coercion is explicit.
  • Dual parsing modes: Use Parse(any) for dynamic data and StrictParse(T) for known Go values.
  • Fluent schema API: Compose primitives, collections, structs, unions, intersections, transforms, refinements, defaults, and metadata.
  • Schema-described output: Object fields, catchall values, defaults, prefaults, transforms, and overwrites return the parsed child output.
  • Struct tags: Build schemas from Go structs with gozod:"..." tags, json/yaml/toml field names, custom tag keys, and circular-reference support.
  • Generated schemas: Use gozodgen for tag-heavy paths where generated helpers are preferable to reflection.
  • Localized errors: Inspect *gozod.ZodError, prettify or flatten failures, and switch message bundles through locales/.
  • JSON Schema bridge: Convert GoZod schemas to JSON Schema and import JSON Schema back into GoZod with explicit lossy-conversion controls.
  • Focused dependency surface: Uses JSON v2, jsonschema, deepclone, JWT parsing, and Unicode helpers without a framework stack.

Installation

go get github.com/kaptinlin/gozod

Requires Go 1.26.5+.

Quick Start

package main

import (
	"fmt"
	"log"

	"github.com/kaptinlin/gozod"
)

func main() {
	email := gozod.String().Min(5).Email()

	value, err := email.Parse("dev@example.com")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(value)
}

Parse and StrictParse

Use Parse(any) at boundaries where input is dynamic. Use StrictParse(T) when your program already has the target Go type.

name := gozod.String().Min(2).Max(50)

fromJSON, err := name.Parse("Alice")
if err != nil {
	log.Fatal(err)
}

knownValue, err := name.StrictParse("Grace")
if err != nil {
	log.Fatal(err)
}

fmt.Println(fromJSON, knownValue)

StrictParse keeps the call site compile-time constrained. Parse keeps the boundary flexible and returns ordinary Go errors.

Struct Tags

Use FromStruct[T]() when validation belongs next to a Go struct. Construction errors report invalid tags or unsupported field types before parsing begins.

package main

import (
	"fmt"
	"log"

	"github.com/kaptinlin/gozod"
)

type User struct {
	Name  string `json:"name" gozod:"required,min=2,max=50"`
	Email string `json:"email" gozod:"required,email"`
	Age   int    `json:"age" gozod:"min=18,max=120"`
}

func main() {
	schema, err := gozod.FromStruct[User]()
	if err != nil {
		log.Fatal(err)
	}

	user, err := schema.Parse(User{
		Name:  "Ada Lovelace",
		Email: "ada@example.com",
		Age:   36,
	})
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%+v\n", user)
}

Use gozod.WithTagName("validate") when your project uses another rule tag, and gozod.WithFieldNameTag("yaml") to resolve field names (error paths and JSON Schema) from yaml/toml tags instead of json. See docs/tags.md for supported tag rules and generated-schema details.

Programmatic Schemas

Use root constructors when you want the schema shape in code.

user := gozod.Object(gozod.ObjectSchema{
	"name":  gozod.String().Min(2),
	"email": gozod.Email(),
	"age":   gozod.Int().Min(18),
})

contact := gozod.Union([]any{
	gozod.Email(),
	gozod.URL(),
})

parsedUser, err := user.Parse(map[string]any{
	"name":  "Grace",
	"email": "grace@example.com",
	"age":   28,
})
if err != nil {
	log.Fatal(err)
}

parsedContact, err := contact.Parse("https://example.com")
if err != nil {
	log.Fatal(err)
}

fmt.Println(parsedUser, parsedContact)

Object parsing returns schema-described output. If a child schema trims, overwrites, transforms, supplies a default, or validates catchall values, the returned map contains that parsed child value.

For conversion-first flows, import coerce/ and choose coercion explicitly.

import "github.com/kaptinlin/gozod/coerce"

age, err := coerce.Int().Parse("42")
if err != nil {
	log.Fatal(err)
}

fmt.Println(age)

Defaults, Prefaults, and Metadata

Default short-circuits validation for nil input. Prefault runs the fallback through the full parsing pipeline.

displayName := gozod.String().Min(3).Default("Guest")
normalized := gozod.String().
	Trim().
	ToLowerCase().
	Prefault("  Example  ")

name, _ := displayName.Parse(nil)
slug, _ := normalized.Parse(nil)

fmt.Println(name, slug)

Metadata modifiers are copy-on-write. The original schema is left unchanged and metadata is stored on the returned schema.

email := gozod.Email().Meta(gozod.GlobalMeta{
	Title:       "Email Address",
	Description: "Primary contact email",
	Examples:    []any{"user@example.com"},
})

meta := email.Internals().Metadata()
fmt.Println(meta.Title)

See docs/metadata.md for registries and JSON Schema metadata merging.

JSON Schema

gozod.ToJSONSchema returns a *jsonschema.Schema from github.com/kaptinlin/jsonschema. Use the exported JSONSchema* mode constants instead of raw strings when setting conversion options.

schema := gozod.Object(gozod.ObjectSchema{
	"name": gozod.String().Min(1),
	"age":  gozod.Int().Min(0),
})

jsonSchema, err := gozod.ToJSONSchema(schema)
if err != nil {
	log.Fatal(err)
}

result := jsonSchema.Validate(map[string]any{
	"name": "Lin",
	"age":  30,
})

fmt.Println(result.IsValid())

gozod.FromJSONSchema fails closed on unsupported JSON Schema keywords. Use gozod.FromJSONSchemaLossy only when dropping unsupported semantics is intentional.

zodSchema, losses, err := gozod.FromJSONSchemaLossy(jsonSchema)
if err != nil {
	log.Fatal(err)
}

_, _ = zodSchema.ParseAny(map[string]any{"name": "Lin", "age": 30})
for _, loss := range losses {
	fmt.Printf("%s at %s: %v\n", loss.Keyword, loss.Pointer, loss.Err)
}

Imported $id, title, description, and examples belong to the returned schema by default. Pass a registry only when the caller needs a separate metadata destination; the importer snapshots nested examples in either mode.

metadata := gozod.NewRegistry[gozod.GlobalMeta]()
zodSchema, err := gozod.FromJSONSchema(jsonSchema, gozod.FromJSONSchemaOptions{
	Metadata: metadata,
})

See docs/json-schema.md for conversion options, unsupported features, registries, and Draft 2020-12 notes.

Error Handling

Validation failures return error. Use GoZod helpers when you need structured inspection or presentation.

schema := gozod.String().Min(5)

_, err := schema.Parse("hi")
if err == nil {
	return
}

var zodErr *gozod.ZodError
if gozod.IsZodError(err, &zodErr) {
	fmt.Println(gozod.PrettifyError(zodErr))
}

See docs/error-customization.md and docs/error-formatting.md.

Code Generation

Install gozodgen when generated struct-tag schemas fit your path better than reflection:

go install github.com/kaptinlin/gozod/cmd/gozodgen@latest
go generate ./...

See cmd/gozodgen and examples/code_generation.

Documentation

Run examples directly:

go run ./examples/quickstart
go run ./examples/struct_tags
go run ./examples/error_handling

Performance

GoZod includes benchmarks for parsing, checks, tags, transforms, and configuration helpers.

  • Prefer StrictParse when the input type is already known.
  • Use coerce/ only when conversion is part of the requirement.
  • Use gozodgen for tag-heavy hot paths where generated helpers are worth the extra file.
go test -bench=. ./...
task bench:smoke

Development

task test                           # Run go test -race ./...
task test:race                      # Run race tests for core and lightweight utility packages
task lint                           # Run golangci-lint and tidy-lint
task golangci-lint                  # Run golangci-lint v2 only
task tidy-lint                      # Verify go.mod and go.sum stay tidy
task contractcheck                  # Run compile-time schema contract checks
task docs:integrity                 # Run public documentation stale-claim checks
task bench:smoke                    # Compile and smoke-run benchmarks without enforcing numbers
task verify:ci                      # Run the CI-equivalent quality gate
task verify                         # Run deps, fmt, vet, lint, contracts, docs, tests, benchmark smoke, and vuln

For development guidelines and repository conventions, see AGENTS.md.

Contributing

Contributions are welcome. Run the test and lint commands before opening a pull request, and keep docs and examples aligned with the current API surface.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Overview

Package gozod provides a TypeScript Zod v4-inspired validation library for Go, offering strongly-typed data validation with intelligent type inference.

Index

Constants

View Source
const (
	IssueInvalidType      = core.InvalidType
	IssueInvalidValue     = core.InvalidValue
	IssueInvalidFormat    = core.InvalidFormat
	IssueInvalidUnion     = core.InvalidUnion
	IssueInvalidKey       = core.InvalidKey
	IssueInvalidElement   = core.InvalidElement
	IssueTooBig           = core.TooBig
	IssueTooSmall         = core.TooSmall
	IssueNotMultipleOf    = core.NotMultipleOf
	IssueUnrecognizedKeys = core.UnrecognizedKeys
	IssueCustom           = core.Custom
)
View Source
const (
	JSONSchemaUnrepresentableThrow = jsonschema.UnrepresentableThrow
	JSONSchemaUnrepresentableAny   = jsonschema.UnrepresentableAny
	JSONSchemaCyclesRef            = jsonschema.CyclesRef
	JSONSchemaCyclesThrow          = jsonschema.CyclesThrow
	JSONSchemaReusedInline         = jsonschema.ReusedInline
	JSONSchemaReusedRef            = jsonschema.ReusedRef
	JSONSchemaTargetDraft202012    = jsonschema.TargetDraft202012
	JSONSchemaIOOutput             = jsonschema.IOOutput
	JSONSchemaIOInput              = jsonschema.IOInput
)

Variables

View Source
var (
	PrecisionMinute      = types.PrecisionMinute
	PrecisionSecond      = types.PrecisionSecond
	PrecisionDecisecond  = types.PrecisionDecisecond
	PrecisionCentisecond = types.PrecisionCentisecond
	PrecisionMillisecond = types.PrecisionMillisecond
	PrecisionMicrosecond = types.PrecisionMicrosecond
	PrecisionNanosecond  = types.PrecisionNanosecond
)
View Source
var (
	ErrNilDiscriminatedUnionOption = types.ErrOptionIsNil
	ErrMissingDiscriminatorValues  = types.ErrNoDiscriminatorValues
	ErrDuplicateDiscriminator      = types.ErrDuplicateDiscriminator
	ErrNoValidDiscriminators       = types.ErrNoValidDiscriminators
)
View Source
var (
	ErrUnsupportedInputType          = jsonschema.ErrUnsupportedInputType
	ErrCircularReference             = jsonschema.ErrCircularReference
	ErrUnrepresentableType           = jsonschema.ErrUnrepresentableType
	ErrSchemaNotObjectOrStruct       = jsonschema.ErrSchemaNotObjectOrStruct
	ErrSliceElementNotSchema         = jsonschema.ErrSliceElementNotSchema
	ErrArrayItemNotSchema            = jsonschema.ErrArrayItemNotSchema
	ErrUnhandledArrayLike            = jsonschema.ErrUnhandledArrayLike
	ErrUnionInvalid                  = jsonschema.ErrUnionInvalid
	ErrUnionNoMembers                = jsonschema.ErrUnionNoMembers
	ErrIntersectionInvalid           = jsonschema.ErrIntersectionInvalid
	ErrInvalidEnumSchema             = jsonschema.ErrInvalidEnumSchema
	ErrEnumExtractValues             = jsonschema.ErrEnumExtractValues
	ErrLiteralNoValuesMethod         = jsonschema.ErrLiteralNoValuesMethod
	ErrLiteralUnexpectedReturnValues = jsonschema.ErrLiteralUnexpectedReturnValues
	ErrExpectedDiscriminatedUnion    = jsonschema.ErrExpectedDiscriminatedUnion
	ErrExpectedRecord                = jsonschema.ErrExpectedRecord
	ErrRecordValueNotSchema          = jsonschema.ErrRecordValueNotSchema
	ErrInvalidRegistrySchemaID       = jsonschema.ErrInvalidRegistrySchemaID
	ErrMapNoMethods                  = jsonschema.ErrMapNoMethods
	ErrMapKeyNotSchema               = jsonschema.ErrMapKeyNotSchema
	ErrMapValueNotSchema             = jsonschema.ErrMapValueNotSchema
	ErrInvalidJSONSchemaOption       = jsonschema.ErrInvalidJSONSchemaOption
	ErrUnsupportedJSONSchemaTarget   = jsonschema.ErrUnsupportedJSONSchemaTarget
	ErrUnsupportedJSONSchemaType     = jsonschema.ErrUnsupportedJSONSchemaType
	ErrUnsupportedJSONSchemaKeyword  = jsonschema.ErrUnsupportedJSONSchemaKeyword
	ErrInvalidJSONSchema             = jsonschema.ErrInvalidJSONSchema
	ErrJSONSchemaCircularRef         = jsonschema.ErrJSONSchemaCircularRef
	ErrJSONSchemaPatternCompile      = jsonschema.ErrJSONSchemaPatternCompile
	ErrJSONSchemaIfThenElse          = jsonschema.ErrJSONSchemaIfThenElse
	ErrJSONSchemaPatternProperties   = jsonschema.ErrJSONSchemaPatternProperties
	ErrJSONSchemaDynamicRef          = jsonschema.ErrJSONSchemaDynamicRef
	ErrJSONSchemaUnevaluatedProps    = jsonschema.ErrJSONSchemaUnevaluatedProps
	ErrJSONSchemaUnevaluatedItems    = jsonschema.ErrJSONSchemaUnevaluatedItems
	ErrJSONSchemaDependentSchemas    = jsonschema.ErrJSONSchemaDependentSchemas
	ErrJSONSchemaPropertyNames       = jsonschema.ErrJSONSchemaPropertyNames
	ErrJSONSchemaContains            = jsonschema.ErrJSONSchemaContains
)
View Source
var GlobalRegistry = core.GlobalRegistry

Functions

func Apply added in v0.5.4

func Apply[S any, R any](schema S, fn func(S) R) R

Apply integrates external functions into schema chains.

func BigInt

func BigInt(params ...any) *types.ZodBigInt[*big.Int]

func BigIntPtr added in v0.3.0

func BigIntPtr(params ...any) *types.ZodBigInt[**big.Int]

func FormatErrorPath added in v0.4.0

func FormatErrorPath(path []any, style string) string

func FromJSONSchemaLossy added in v0.11.8

func FromJSONSchemaLossy(
	schema *lib.Schema,
	opts ...FromJSONSchemaOptions,
) (ZodSchema, []JSONSchemaImportLossError, error)

FromJSONSchemaLossy converts a JSON Schema and reports omitted validation semantics.

func FromStruct added in v0.5.0

func FromStruct[T any](opts ...FromStructOption) (*types.ZodStruct[T, T], error)

func FromStructPtr added in v0.5.0

func FromStructPtr[T any](opts ...FromStructOption) (*types.ZodStruct[T, *T], error)

func IsZodError

func IsZodError(err error, target **ZodError) bool

func Lazy

func Lazy[S types.ZodSchemaType](getter func() S, params ...any) *types.ZodLazyTyped[S]

func LazyTyped added in v0.11.8

func LazyTyped[T types.LazyConstraint](getter func() any, params ...any) *types.ZodLazyOutput[T]

func MustFromStruct added in v0.11.8

func MustFromStruct[T any](opts ...FromStructOption) *types.ZodStruct[T, T]

func MustFromStructPtr added in v0.11.8

func MustFromStructPtr[T any](opts ...FromStructOption) *types.ZodStruct[T, *T]

func PrettifyError

func PrettifyError(zodErr *ZodError) string

func PrettifyErrorWithFormatter added in v0.3.0

func PrettifyErrorWithFormatter(zodErr *ZodError, formatter MessageFormatter) string

func ToDotPath

func ToDotPath(path []any) string

func ToJSONSchema added in v0.3.1

func ToJSONSchema(input any, opts ...JSONSchemaOptions) (*lib.Schema, error)

ToJSONSchema converts a GoZod schema or registry into JSON Schema.

func Xor added in v0.5.4

func Xor(options []any, args ...any) *types.ZodXor[any, any]

func XorOf added in v0.5.4

func XorOf(schemas ...any) *types.ZodXor[any, any]

func XorPtr added in v0.5.4

func XorPtr(options []any, args ...any) *types.ZodXor[any, *any]

Types

type CheckParams added in v0.3.0

type CheckParams = core.CheckParams

type CustomParams added in v0.3.1

type CustomParams = core.CustomParams

type DiscriminatorError added in v0.11.8

type DiscriminatorError = types.DiscriminatorError

type FlattenedError

type FlattenedError = issues.FlattenedError

func FlattenError

func FlattenError(zodErr *ZodError) *FlattenedError

func FlattenErrorWithFormatter added in v0.3.0

func FlattenErrorWithFormatter(zodErr *ZodError, formatter MessageFormatter) *FlattenedError

func FlattenErrorWithMapper

func FlattenErrorWithMapper(zodErr *ZodError, mapper func(ZodIssue) string) *FlattenedError

type FromJSONSchemaOptions added in v0.5.4

type FromJSONSchemaOptions = jsonschema.FromJSONSchemaOptions

type FromStructOption added in v0.8.0

type FromStructOption = types.FromStructOption

func WithFieldNameTag added in v0.11.6

func WithFieldNameTag(name string) FromStructOption

WithFieldNameTag sets the struct tag used for field names (e.g. "yaml", "toml"). It defaults to "json".

func WithTagName added in v0.8.0

func WithTagName(name string) FromStructOption

type GlobalMeta added in v0.3.1

type GlobalMeta = core.GlobalMeta

type IsoDatetimeOptions added in v0.3.0

type IsoDatetimeOptions = types.IsoDatetimeOptions

Public schema type aliases.

type IsoTimeOptions added in v0.3.0

type IsoTimeOptions = types.IsoTimeOptions

Public schema type aliases.

type IssueCode

type IssueCode = core.IssueCode

type JSONSchemaCyclesMode added in v0.11.7

type JSONSchemaCyclesMode = jsonschema.CyclesMode

type JSONSchemaIOMode added in v0.11.7

type JSONSchemaIOMode = jsonschema.IOMode

type JSONSchemaImportError added in v0.11.8

type JSONSchemaImportError = jsonschema.ImportError

type JSONSchemaImportLossError added in v0.11.8

type JSONSchemaImportLossError = jsonschema.ImportLossError

type JSONSchemaOptions added in v0.3.1

type JSONSchemaOptions = jsonschema.Options

type JSONSchemaReusedMode added in v0.11.7

type JSONSchemaReusedMode = jsonschema.ReusedMode

type JSONSchemaTargetMode added in v0.11.7

type JSONSchemaTargetMode = jsonschema.TargetMode

type JSONSchemaUnrepresentableMode added in v0.11.7

type JSONSchemaUnrepresentableMode = jsonschema.UnrepresentableMode

type JWTOptions added in v0.3.0

type JWTOptions = types.JWTOptions

Public schema type aliases.

type MessageFormatter added in v0.3.0

type MessageFormatter = issues.MessageFormatter

type ObjectSchema

type ObjectSchema = core.ObjectSchema

type OverrideContext added in v0.3.1

type OverrideContext = jsonschema.OverrideContext

type ParsePayload

type ParsePayload = core.ParsePayload

type Registry added in v0.3.1

type Registry[M any] = core.Registry[M]

func NewRegistry added in v0.3.1

func NewRegistry[M any]() *Registry[M]

type SchemaParams

type SchemaParams = core.SchemaParams

type StructSchema added in v0.2.0

type StructSchema = core.StructSchema

type URLOptions added in v0.3.0

type URLOptions = types.URLOptions

Public schema type aliases.

type Unwrapper added in v0.8.0

type Unwrapper = core.Unwrapper

Unwrapper allows wrapper types to expose their underlying value for validation.

type ZodAny

type ZodAny[T any, R any] = types.ZodAny[T, R]

Public schema type aliases.

func Any

func Any(params ...any) *ZodAny[any, any]

func AnyPtr added in v0.3.0

func AnyPtr(params ...any) *ZodAny[any, *any]

type ZodArray

type ZodArray[T any, R any] = types.ZodArray[T, R]

Public schema type aliases.

func Array

func Array(args ...any) *ZodArray[[]any, []any]

func ArrayPtr added in v0.3.0

func ArrayPtr(args ...any) *ZodArray[[]any, *[]any]

type ZodBase64 added in v0.3.0

type ZodBase64[T types.StringConstraint] = types.ZodBase64[T]

Public schema type aliases.

func Base64 added in v0.3.0

func Base64(params ...any) *ZodBase64[string]

func Base64Ptr added in v0.3.0

func Base64Ptr(params ...any) *ZodBase64[*string]

type ZodBase64URL added in v0.3.0

type ZodBase64URL[T types.StringConstraint] = types.ZodBase64URL[T]

Public schema type aliases.

func Base64URL added in v0.3.0

func Base64URL(params ...any) *ZodBase64URL[string]

func Base64URLPtr added in v0.3.0

func Base64URLPtr(params ...any) *ZodBase64URL[*string]

type ZodBool

type ZodBool[T types.BoolConstraint] = types.ZodBool[T]

Public schema type aliases.

func Bool

func Bool(params ...any) *ZodBool[bool]

func BoolPtr added in v0.3.0

func BoolPtr(params ...any) *ZodBool[*bool]

type ZodCIDRv4

type ZodCIDRv4[T types.StringConstraint] = types.ZodCIDRv4[T]

Public schema type aliases.

func CIDRv4

func CIDRv4(params ...any) *ZodCIDRv4[string]

func CIDRv4Ptr added in v0.3.0

func CIDRv4Ptr(params ...any) *ZodCIDRv4[*string]

type ZodCIDRv6

type ZodCIDRv6[T types.StringConstraint] = types.ZodCIDRv6[T]

Public schema type aliases.

func CIDRv6

func CIDRv6(params ...any) *ZodCIDRv6[string]

func CIDRv6Ptr added in v0.3.0

func CIDRv6Ptr(params ...any) *ZodCIDRv6[*string]

type ZodCUID added in v0.3.0

type ZodCUID[T types.StringConstraint] = types.ZodCUID[T]

Public schema type aliases.

func CUID added in v0.7.0

func CUID(params ...any) *ZodCUID[string]

func CUIDPtr added in v0.7.0

func CUIDPtr(params ...any) *ZodCUID[*string]

type ZodCUID2 added in v0.3.0

type ZodCUID2[T types.StringConstraint] = types.ZodCUID2[T]

Public schema type aliases.

func CUID2 added in v0.7.0

func CUID2(params ...any) *ZodCUID2[string]

func CUID2Ptr added in v0.7.0

func CUID2Ptr(params ...any) *ZodCUID2[*string]

type ZodCheck

type ZodCheck = core.ZodCheck

type ZodCheckDef

type ZodCheckDef = core.ZodCheckDef

type ZodCheckFn

type ZodCheckFn = core.ZodCheckFn

type ZodCheckInternals

type ZodCheckInternals = core.ZodCheckInternals

type ZodComplex

type ZodComplex[T types.ComplexConstraint] = types.ZodComplex[T]

Public schema type aliases.

func Complex added in v0.3.0

func Complex(params ...any) *ZodComplex[complex128]

func Complex64

func Complex64(params ...any) *ZodComplex[complex64]

func Complex64Ptr added in v0.3.0

func Complex64Ptr(params ...any) *ZodComplex[*complex64]

func Complex128

func Complex128(params ...any) *ZodComplex[complex128]

func Complex128Ptr added in v0.3.0

func Complex128Ptr(params ...any) *ZodComplex[*complex128]

func ComplexPtr added in v0.3.0

func ComplexPtr(params ...any) *ZodComplex[*complex128]

type ZodConfig

type ZodConfig = core.ZodConfig

func Config

func Config() *ZodConfig

func SetConfig added in v0.6.0

func SetConfig(config *ZodConfig) *ZodConfig

type ZodDiscriminatedUnion

type ZodDiscriminatedUnion[T any, R any] = types.ZodDiscriminatedUnion[T, R]

Public schema type aliases.

func DiscriminatedUnion

func DiscriminatedUnion(disc string, options []core.ZodSchema, args ...any) (*ZodDiscriminatedUnion[any, any], error)

func DiscriminatedUnionPtr added in v0.3.0

func DiscriminatedUnionPtr(disc string, options []core.ZodSchema, args ...any) (*ZodDiscriminatedUnion[any, *any], error)

func MustDiscriminatedUnion added in v0.11.8

func MustDiscriminatedUnion(disc string, options []core.ZodSchema, args ...any) *ZodDiscriminatedUnion[any, any]

func MustDiscriminatedUnionPtr added in v0.11.8

func MustDiscriminatedUnionPtr(disc string, options []core.ZodSchema, args ...any) *ZodDiscriminatedUnion[any, *any]

type ZodE164 added in v0.5.4

type ZodE164[T types.StringConstraint] = types.ZodE164[T]

Public schema type aliases.

func E164 added in v0.5.4

func E164(params ...any) *ZodE164[string]

func E164Ptr added in v0.5.4

func E164Ptr(params ...any) *ZodE164[*string]

type ZodEmail added in v0.3.0

type ZodEmail[T types.EmailConstraint] = types.ZodEmail[T]

Public schema type aliases.

func Email added in v0.3.0

func Email(params ...any) *ZodEmail[string]

func EmailPtr added in v0.3.0

func EmailPtr(params ...any) *ZodEmail[*string]

type ZodEmoji added in v0.3.0

type ZodEmoji[T types.StringConstraint] = types.ZodEmoji[T]

Public schema type aliases.

func Emoji added in v0.3.0

func Emoji(params ...any) *ZodEmoji[string]

func EmojiPtr added in v0.3.0

func EmojiPtr(params ...any) *ZodEmoji[*string]

type ZodEnum

type ZodEnum[T comparable, R any] = types.ZodEnum[T, R]

Public schema type aliases.

func Enum

func Enum[T comparable](values ...T) *ZodEnum[T, T]

func EnumMap

func EnumMap[T comparable](entries map[string]T, params ...any) *ZodEnum[T, T]

func EnumMapPtr added in v0.3.0

func EnumMapPtr[T comparable](entries map[string]T, params ...any) *ZodEnum[T, *T]

func EnumPtr added in v0.3.0

func EnumPtr[T comparable](values ...T) *ZodEnum[T, *T]

func EnumSlice

func EnumSlice[T comparable](values []T) *ZodEnum[T, T]

func EnumSlicePtr added in v0.3.0

func EnumSlicePtr[T comparable](values []T) *ZodEnum[T, *T]

type ZodError

type ZodError = issues.ZodError

type ZodErrorTree

type ZodErrorTree = issues.ZodErrorTree

func TreeifyError

func TreeifyError(zodErr *ZodError) *ZodErrorTree

func TreeifyErrorWithMapper

func TreeifyErrorWithMapper(zodErr *ZodError, mapper func(ZodIssue) string) *ZodErrorTree

type ZodFile

type ZodFile[T any, R any] = types.ZodFile[T, R]

Public schema type aliases.

func File

func File(params ...any) *ZodFile[any, any]

func FilePtr added in v0.3.0

func FilePtr(params ...any) *ZodFile[any, *any]

type ZodFloat

type ZodFloat[T types.FloatConstraint, R any] = types.ZodFloat[T, R]

Public schema type aliases.

func Float added in v0.3.0

func Float(params ...any) *ZodFloat[float64, float64]

func Float32

func Float32(params ...any) *ZodFloat[float32, float32]

func Float32Ptr added in v0.3.0

func Float32Ptr(params ...any) *ZodFloat[float32, *float32]

func Float64

func Float64(params ...any) *ZodFloat[float64, float64]

func Float64Ptr added in v0.3.0

func Float64Ptr(params ...any) *ZodFloat[float64, *float64]

func FloatPtr added in v0.3.0

func FloatPtr(params ...any) *ZodFloat[float64, *float64]

func Number

func Number(params ...any) *ZodFloat[float64, float64]

func NumberPtr added in v0.3.0

func NumberPtr(params ...any) *ZodFloat[float64, *float64]

type ZodFormattedError

type ZodFormattedError = issues.ZodFormattedError

func FormatError

func FormatError(zodErr *ZodError) ZodFormattedError

type ZodFunction

type ZodFunction[T types.FunctionConstraint] = types.ZodFunction[T]

Public schema type aliases.

func Function

func Function(params ...any) *ZodFunction[any]

func FunctionPtr added in v0.3.0

func FunctionPtr(params ...any) *ZodFunction[*any]

type ZodGUID added in v0.5.5

type ZodGUID[T types.StringConstraint] = types.ZodGUID[T]

Public schema type aliases.

func GUID added in v0.7.0

func GUID(params ...any) *ZodGUID[string]

func GUIDPtr added in v0.7.0

func GUIDPtr(params ...any) *ZodGUID[*string]

type ZodHex added in v0.5.4

type ZodHex[T types.StringConstraint] = types.ZodHex[T]

Public schema type aliases.

func Hex added in v0.5.4

func Hex(params ...any) *ZodHex[string]

func HexPtr added in v0.5.4

func HexPtr(params ...any) *ZodHex[*string]

type ZodHostname added in v0.5.4

type ZodHostname[T types.StringConstraint] = types.ZodHostname[T]

Public schema type aliases.

func Hostname added in v0.5.4

func Hostname(params ...any) *ZodHostname[string]

func HostnamePtr added in v0.5.4

func HostnamePtr(params ...any) *ZodHostname[*string]

type ZodIPv4

type ZodIPv4[T types.StringConstraint] = types.ZodIPv4[T]

Public schema type aliases.

func IPv4

func IPv4(params ...any) *ZodIPv4[string]

func IPv4Ptr added in v0.3.0

func IPv4Ptr(params ...any) *ZodIPv4[*string]

type ZodIPv6

type ZodIPv6[T types.StringConstraint] = types.ZodIPv6[T]

Public schema type aliases.

func IPv6

func IPv6(params ...any) *ZodIPv6[string]

func IPv6Ptr added in v0.3.0

func IPv6Ptr(params ...any) *ZodIPv6[*string]

type ZodInteger

type ZodInteger[T types.IntegerConstraint, R any] = types.ZodInteger[T, R]

Public schema type aliases.

func Int

func Int(params ...any) *ZodInteger[int, int]

func Int8

func Int8(params ...any) *ZodInteger[int8, int8]

func Int8Ptr added in v0.3.0

func Int8Ptr(params ...any) *ZodInteger[int8, *int8]

func Int16

func Int16(params ...any) *ZodInteger[int16, int16]

func Int16Ptr added in v0.3.0

func Int16Ptr(params ...any) *ZodInteger[int16, *int16]

func Int32

func Int32(params ...any) *ZodInteger[int32, int32]

func Int32Ptr added in v0.3.0

func Int32Ptr(params ...any) *ZodInteger[int32, *int32]

func Int64

func Int64(params ...any) *ZodInteger[int64, int64]

func Int64Ptr added in v0.3.0

func Int64Ptr(params ...any) *ZodInteger[int64, *int64]

func IntPtr added in v0.3.0

func IntPtr(params ...any) *ZodInteger[int, *int]

func Uint

func Uint(params ...any) *ZodInteger[uint, uint]

func Uint8

func Uint8(params ...any) *ZodInteger[uint8, uint8]

func Uint8Ptr added in v0.3.0

func Uint8Ptr(params ...any) *ZodInteger[uint8, *uint8]

func Uint16

func Uint16(params ...any) *ZodInteger[uint16, uint16]

func Uint16Ptr added in v0.3.0

func Uint16Ptr(params ...any) *ZodInteger[uint16, *uint16]

func Uint32

func Uint32(params ...any) *ZodInteger[uint32, uint32]

func Uint32Ptr added in v0.3.0

func Uint32Ptr(params ...any) *ZodInteger[uint32, *uint32]

func Uint64

func Uint64(params ...any) *ZodInteger[uint64, uint64]

func Uint64Ptr added in v0.3.0

func Uint64Ptr(params ...any) *ZodInteger[uint64, *uint64]

func UintPtr added in v0.3.0

func UintPtr(params ...any) *ZodInteger[uint, *uint]

type ZodIntersection

type ZodIntersection[T any, R any] = types.ZodIntersection[T, R]

Public schema type aliases.

func Intersection

func Intersection(left, right any, args ...any) *ZodIntersection[any, any]

func IntersectionPtr added in v0.3.0

func IntersectionPtr(left, right any, args ...any) *ZodIntersection[any, *any]

type ZodIso added in v0.3.0

type ZodIso[T types.IsoConstraint] = types.ZodIso[T]

Public schema type aliases.

func Iso added in v0.3.0

func Iso(params ...any) *ZodIso[string]

func IsoDate added in v0.3.0

func IsoDate(params ...any) *ZodIso[string]

func IsoDatePtr added in v0.3.0

func IsoDatePtr(params ...any) *ZodIso[*string]

func IsoDateTime added in v0.3.0

func IsoDateTime(params ...any) *ZodIso[string]

func IsoDateTimePtr added in v0.3.0

func IsoDateTimePtr(params ...any) *ZodIso[*string]

func IsoDuration added in v0.3.0

func IsoDuration(params ...any) *ZodIso[string]

func IsoDurationPtr added in v0.3.0

func IsoDurationPtr(params ...any) *ZodIso[*string]

func IsoPtr added in v0.3.0

func IsoPtr(params ...any) *ZodIso[*string]

func IsoTime added in v0.3.0

func IsoTime(params ...any) *ZodIso[string]

func IsoTimePtr added in v0.3.0

func IsoTimePtr(params ...any) *ZodIso[*string]

type ZodIssue

type ZodIssue = core.ZodIssue

type ZodJWT added in v0.3.0

type ZodJWT[T types.StringConstraint] = types.ZodJWT[T]

Public schema type aliases.

func JWT added in v0.3.0

func JWT(params ...any) *ZodJWT[string]

func JWTPtr added in v0.3.0

func JWTPtr(params ...any) *ZodJWT[*string]

type ZodKSUID added in v0.3.0

type ZodKSUID[T types.StringConstraint] = types.ZodKSUID[T]

Public schema type aliases.

func KSUID added in v0.7.0

func KSUID(params ...any) *ZodKSUID[string]

func KSUIDPtr added in v0.7.0

func KSUIDPtr(params ...any) *ZodKSUID[*string]

type ZodLazy

type ZodLazy[T types.LazyConstraint] = types.ZodLazy[T]

Public schema type aliases.

func LazyAny added in v0.3.0

func LazyAny(getter func() any, params ...any) *ZodLazy[any]

func LazyPtr added in v0.3.0

func LazyPtr(getter func() any, params ...any) *ZodLazy[*any]

type ZodLiteral

type ZodLiteral[T comparable, R any] = types.ZodLiteral[T, R]

Public schema type aliases.

func Literal

func Literal[T comparable](value T, params ...any) *ZodLiteral[T, T]

func LiteralOf added in v0.3.0

func LiteralOf[T comparable](values []T, params ...any) *ZodLiteral[T, T]

func LiteralPtr added in v0.3.0

func LiteralPtr[T comparable](value T, params ...any) *ZodLiteral[T, *T]

func LiteralPtrOf added in v0.3.0

func LiteralPtrOf[T comparable](values []T, params ...any) *ZodLiteral[T, *T]

type ZodMAC added in v0.5.4

type ZodMAC[T types.StringConstraint] = types.ZodMAC[T]

Public schema type aliases.

func MAC added in v0.5.4

func MAC(params ...any) *ZodMAC[string]

func MACPtr added in v0.5.4

func MACPtr(params ...any) *ZodMAC[*string]

func MACWithDelimiter added in v0.5.4

func MACWithDelimiter(delimiter string, params ...any) *ZodMAC[string]

type ZodMap

type ZodMap[T any, R any] = types.ZodMap[T, R]

Public schema type aliases.

func Map

func Map(keySchema, valueSchema any, paramArgs ...any) *ZodMap[map[any]any, map[any]any]

func MapPtr added in v0.3.0

func MapPtr(keySchema, valueSchema any, paramArgs ...any) *ZodMap[map[any]any, *map[any]any]

type ZodNanoID added in v0.3.0

type ZodNanoID[T types.StringConstraint] = types.ZodNanoID[T]

Public schema type aliases.

func NanoID added in v0.7.0

func NanoID(params ...any) *ZodNanoID[string]

func NanoIDPtr added in v0.7.0

func NanoIDPtr(params ...any) *ZodNanoID[*string]

type ZodNever

type ZodNever[T any, R any] = types.ZodNever[T, R]

Public schema type aliases.

func Never

func Never(params ...any) *ZodNever[any, any]

func NeverPtr added in v0.3.0

func NeverPtr(params ...any) *ZodNever[any, *any]

type ZodNil

type ZodNil[T any, R any] = types.ZodNil[T, R]

Public schema type aliases.

func Nil

func Nil(params ...any) *ZodNil[any, any]

func NilPtr added in v0.3.0

func NilPtr(params ...any) *ZodNil[any, *any]

type ZodObject

type ZodObject[T any, R any] = types.ZodObject[T, R]

Public schema type aliases.

func LooseObject

func LooseObject(shape core.ObjectSchema, params ...any) *ZodObject[map[string]any, map[string]any]

func LooseObjectPtr added in v0.3.0

func LooseObjectPtr(shape core.ObjectSchema, params ...any) *ZodObject[map[string]any, *map[string]any]

func Object

func Object(shape core.ObjectSchema, params ...any) *ZodObject[map[string]any, map[string]any]

func ObjectPtr added in v0.3.0

func ObjectPtr(shape core.ObjectSchema, params ...any) *ZodObject[map[string]any, *map[string]any]

func StrictObject

func StrictObject(shape core.ObjectSchema, params ...any) *ZodObject[map[string]any, map[string]any]

func StrictObjectPtr added in v0.3.0

func StrictObjectPtr(shape core.ObjectSchema, params ...any) *ZodObject[map[string]any, *map[string]any]

type ZodRawIssue

type ZodRawIssue = core.ZodRawIssue

type ZodRecord

type ZodRecord[T any, R any] = types.ZodRecord[T, R]

Public schema type aliases.

func LooseRecord added in v0.5.4

func LooseRecord(keySchema, valueSchema any, paramArgs ...any) *ZodRecord[map[string]any, map[string]any]

func LooseRecordPtr added in v0.5.4

func LooseRecordPtr(keySchema, valueSchema any, paramArgs ...any) *ZodRecord[map[string]any, *map[string]any]

func Record

func Record[K any, V any](keySchema any, valueSchema core.ZodType[V], paramArgs ...any) *ZodRecord[map[string]V, map[string]V]

func RecordPtr added in v0.3.0

func RecordPtr[K any, V any](keySchema any, valueSchema core.ZodType[V], paramArgs ...any) *ZodRecord[map[string]V, *map[string]V]

type ZodRefineFn added in v0.3.0

type ZodRefineFn[T any] = core.ZodRefineFn[T]

type ZodSchema added in v0.11.7

type ZodSchema = core.ZodSchema

ZodSchema is the non-generic runtime schema interface.

func FromJSONSchema added in v0.5.4

func FromJSONSchema(schema *lib.Schema, opts ...FromJSONSchemaOptions) (ZodSchema, error)

FromJSONSchema converts JSON Schema into a GoZod schema.

type ZodSet added in v0.5.5

type ZodSet[T comparable, R any] = types.ZodSet[T, R]

Public schema type aliases.

func Set added in v0.5.5

func Set[T comparable](valueSchema any, paramArgs ...any) *ZodSet[T, map[T]struct{}]

func SetPtr added in v0.5.5

func SetPtr[T comparable](valueSchema any, paramArgs ...any) *ZodSet[T, *map[T]struct{}]

type ZodSlice

type ZodSlice[T any, R any] = types.ZodSlice[T, R]

Public schema type aliases.

func Slice

func Slice[T any](elementSchema any, paramArgs ...any) *ZodSlice[T, []T]

func SlicePtr added in v0.3.0

func SlicePtr[T any](elementSchema any, paramArgs ...any) *ZodSlice[T, *[]T]

type ZodString

type ZodString[T types.StringConstraint] = types.ZodString[T]

Public schema type aliases.

func String

func String(params ...any) *ZodString[string]

func StringPtr added in v0.3.0

func StringPtr(params ...any) *ZodString[*string]

type ZodStringBool

type ZodStringBool[T types.StringBoolConstraint] = types.ZodStringBool[T]

Public schema type aliases.

func StringBool

func StringBool(params ...any) *ZodStringBool[bool]

func StringBoolPtr added in v0.3.0

func StringBoolPtr(params ...any) *ZodStringBool[*bool]

type ZodStruct

type ZodStruct[T any, R any] = types.ZodStruct[T, R]

Public schema type aliases.

func Struct

func Struct[T any](params ...any) *ZodStruct[T, T]

func StructPtr added in v0.3.0

func StructPtr[T any](params ...any) *ZodStruct[T, *T]

type ZodTime added in v0.3.0

type ZodTime[T types.TimeConstraint] = types.ZodTime[T]

Public schema type aliases.

func Time added in v0.3.0

func Time(params ...any) *ZodTime[time.Time]

func TimePtr added in v0.3.0

func TimePtr(params ...any) *ZodTime[*time.Time]

type ZodTuple added in v0.5.4

type ZodTuple[T any, R any] = types.ZodTuple[T, R]

Public schema type aliases.

func Tuple added in v0.5.4

func Tuple(items ...core.ZodSchema) *ZodTuple[[]any, []any]

func TuplePtr added in v0.5.4

func TuplePtr(items ...core.ZodSchema) *ZodTuple[[]any, *[]any]

func TupleWithRest added in v0.5.4

func TupleWithRest(items []core.ZodSchema, rest core.ZodSchema, params ...any) *ZodTuple[[]any, []any]

type ZodType

type ZodType[T any] = core.ZodType[T]

ZodType is a generic alias for core.ZodType for ergonomic use.

type ZodULID added in v0.3.0

type ZodULID[T types.StringConstraint] = types.ZodULID[T]

Public schema type aliases.

func ULID added in v0.7.0

func ULID(params ...any) *ZodULID[string]

func ULIDPtr added in v0.7.0

func ULIDPtr(params ...any) *ZodULID[*string]

type ZodURL added in v0.3.0

type ZodURL[T types.StringConstraint] = types.ZodURL[T]

Public schema type aliases.

func HTTPURL added in v0.6.0

func HTTPURL(params ...any) *ZodURL[string]

func HTTPURLPtr added in v0.6.0

func HTTPURLPtr(params ...any) *ZodURL[*string]

func URL added in v0.3.0

func URL(params ...any) *ZodURL[string]

func URLPtr added in v0.3.0

func URLPtr(params ...any) *ZodURL[*string]

type ZodUUID added in v0.3.0

type ZodUUID[T types.StringConstraint] = types.ZodUUID[T]

Public schema type aliases.

func UUID added in v0.7.0

func UUID(params ...any) *ZodUUID[string]

func UUIDPtr added in v0.7.0

func UUIDPtr(params ...any) *ZodUUID[*string]

func UUIDv4 added in v0.7.0

func UUIDv4(params ...any) *ZodUUID[string]

func UUIDv4Ptr added in v0.7.0

func UUIDv4Ptr(params ...any) *ZodUUID[*string]

func UUIDv6 added in v0.7.0

func UUIDv6(params ...any) *ZodUUID[string]

func UUIDv6Ptr added in v0.7.0

func UUIDv6Ptr(params ...any) *ZodUUID[*string]

func UUIDv7 added in v0.7.0

func UUIDv7(params ...any) *ZodUUID[string]

func UUIDv7Ptr added in v0.7.0

func UUIDv7Ptr(params ...any) *ZodUUID[*string]

type ZodUnion

type ZodUnion[T any, R any] = types.ZodUnion[T, R]

Public schema type aliases.

func Union

func Union(options []any, args ...any) *ZodUnion[any, any]

func UnionPtr added in v0.3.0

func UnionPtr(options []any, args ...any) *ZodUnion[any, *any]

type ZodUnknown

type ZodUnknown[T any, R any] = types.ZodUnknown[T, R]

Public schema type aliases.

func Unknown

func Unknown(params ...any) *ZodUnknown[any, any]

func UnknownPtr added in v0.3.0

func UnknownPtr(params ...any) *ZodUnknown[any, *any]

type ZodWhenFn

type ZodWhenFn = core.ZodWhenFn

type ZodXID added in v0.3.0

type ZodXID[T types.StringConstraint] = types.ZodXID[T]

Public schema type aliases.

func XID added in v0.7.0

func XID(params ...any) *ZodXID[string]

func XIDPtr added in v0.7.0

func XIDPtr(params ...any) *ZodXID[*string]

Directories

Path Synopsis
cmd
gozodgen command
Package main implements the gozodgen code generation tool.
Package main implements the gozodgen code generation tool.
gozodgen/coercionfixture
Package coercionfixture verifies generated coercion parity.
Package coercionfixture verifies generated coercion parity.
gozodgen/providerfixture
Package providerfixture verifies generated schema dependency graphs.
Package providerfixture verifies generated schema dependency graphs.
Package coerce provides constructors that enable automatic type coercion before validation.
Package coerce provides constructors that enable automatic type coercion before validation.
Package core provides the foundation contracts for the gozod validation library, including interfaces, types, and constants used throughout the system.
Package core provides the foundation contracts for the gozod validation library, including interfaces, types, and constants used throughout the system.
examples
advanced_lazy command
code_generation command
Package main demonstrates explicit GoZod schema generation from struct tags.
Package main demonstrates explicit GoZod schema generation from struct tags.
coerce command
config command
custom_tag command
error_handling command
format command
i18n command
intersection command
object command
primitive command
quickstart command
struct_tags command
Package main demonstrates GoZod struct tag validation usage This example covers the most important features in a simple, practical way.
Package main demonstrates GoZod struct tag validation usage This example covers the most important features in a simple, practical way.
union command
internal
checks
Package checks provides validation check factories for the GoZod validation library.
Package checks provides validation check factories for the GoZod validation library.
engine
Package engine provides the core parsing and validation engine for GoZod schemas.
Package engine provides the core parsing and validation engine for GoZod schemas.
issues
Package issues provides error creation, formatting, and management for GoZod validation.
Package issues provides error creation, formatting, and management for GoZod validation.
utils
Package utils provides internal utility functions for the gozod validation library, including error map conversion, parameter normalization, value origin detection, value comparison, and error path formatting.
Package utils provides internal utility functions for the gozod validation library, including error map conversion, parameter normalization, value origin detection, value comparison, and error path formatting.
Package jsonschema provides JSON Schema conversion for GoZod schemas.
Package jsonschema provides JSON Schema conversion for GoZod schemas.
Package locales provides pre-configured error message formatters for different languages.
Package locales provides pre-configured error message formatters for different languages.
pkg
cloneutil
Package cloneutil centralizes deep-copy behavior for GoZod runtime values and schema internals while preserving library-specific semantics.
Package cloneutil centralizes deep-copy behavior for GoZod runtime values and schema internals while preserving library-specific semantics.
coerce
Package coerce provides type coercion utilities for converting values between different Go types with proper error handling and overflow detection.
Package coerce provides type coercion utilities for converting values between different Go types with proper error handling and overflow detection.
mapx
Package mapx provides type-safe utility functions for working with Go maps.
Package mapx provides type-safe utility functions for working with Go maps.
reflectx
Package reflectx provides reflection utilities for type checking and value manipulation.
Package reflectx provides reflection utilities for type checking and value manipulation.
regex
Package regex provides pre-compiled regular expressions for common data formats.
Package regex provides pre-compiled regular expressions for common data formats.
slicex
Package slicex provides utility functions for working with Go slices.
Package slicex provides utility functions for working with Go slices.
structx
Package structx converts between Go structs and map[string]any.
Package structx converts between Go structs and map[string]any.
tagparser
Package tagparser parses struct-tag validation rules into a reusable representation shared by GoZod runtime code and codegen.
Package tagparser parses struct-tag validation rules into a reusable representation shared by GoZod runtime code and codegen.
transform
Package transform provides string and data transformation utilities such as slugifying strings for URL-friendly formats.
Package transform provides string and data transformation utilities such as slugifying strings for URL-friendly formats.
validate
Package validate provides validation functions for various data types and formats.
Package validate provides validation functions for various data types and formats.
Package types provides public schema implementations for GoZod validation types.
Package types provides public schema implementations for GoZod validation types.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL