gozod

package module
v0.8.1 Latest Latest
Warning

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

Go to latest
Published: Mar 17, 2026 License: MIT Imports: 6 Imported by: 1

README

GoZod 🔷

GoZod is a TypeScript Zod v4-inspired validation library for Go, providing strongly-typed, zero-dependency data validation with intelligent type inference and maximum performance.

Go Version License Test Status

✨ Key Features

  • TypeScript Zod v4 Compatible API - Familiar syntax with Go-native optimizations
  • Complete Strict Type Semantics - All methods require exact input types, zero automatic conversions
  • 🏷️ Declarative Struct Tags - Define validation rules directly on struct fields with gozod:"required,min=2,email"
  • Parse vs StrictParse - Runtime flexibility or compile-time type safety for optimal performance
  • Native Go Struct Support - First-class struct validation with field-level validation and JSON tag mapping
  • Automatic Circular Reference Handling - Lazy evaluation prevents stack overflow in recursive structures
  • Maximum Performance - Zero-overhead validation with optional code generation (5-10x faster)
  • Zero Dependencies - Pure Go implementation, no external libraries
  • Rich Validation Methods - Comprehensive built-in validators for all Go types

Why GoZod?

  • 🎯 Type Safety First - Compile-time guarantees with runtime flexibility
  • ⚡ Maximum Performance - Zero-overhead abstractions with optional code generation
  • 🏷️ Developer Experience - Familiar API with Go idioms and declarative struct tags
  • 🔒 Production Ready - Battle-tested validation with comprehensive error handling
  • 🌟 Zero Dependencies - Pure Go implementation, no external dependencies

GoZod brings TypeScript Zod's excellent developer experience to Go while embracing Go's type system and performance characteristics. Perfect for API validation, configuration parsing, data transformation, and any scenario where type-safe validation is critical.

📦 Quick Start

Installation
go get github.com/kaptinlin/gozod
Basic Usage
package main

import (
    "fmt"
    "github.com/kaptinlin/gozod"
)

func main() {
    // String validation with method chaining
    nameSchema := gozod.String().Min(2).Max(50)
    
    // Parse - Runtime type checking (flexible)
    result, err := nameSchema.Parse("Alice")
    if err == nil {
        fmt.Println("Valid name:", result) // "Alice"
    }

    // StrictParse - Compile-time type safety (optimal performance)
    name := "Alice"
    result, err = nameSchema.StrictParse(name) // Input type guaranteed
    if err == nil {
        fmt.Println("Validated name:", result)
    }

    // Email validation
    emailSchema := gozod.String().Email()
    email := "user@example.com"
    result, err = emailSchema.StrictParse(email)
    if err == nil {
        fmt.Printf("Valid email: %s\n", result)
    }
}
Struct Tag Validation (Declarative)
package main

import (
    "fmt"
    "github.com/kaptinlin/gozod"
)

type User struct {
    Name  string `gozod:"required,min=2,max=50"`
    Email string `gozod:"required,email"`
    Age   int    `gozod:"required,min=18,max=120"`
    Bio   string `gozod:"max=500"`           // Optional by default
}

func main() {
    // Generate schema from struct tags
    schema := gozod.FromStruct[User]()
    
    user := User{
        Name:  "Alice Johnson",
        Email: "alice@example.com",
        Age:   28,
        Bio:   "Software engineer",
    }
    
    // Validate with generated schema
    validatedUser, err := schema.Parse(user)
    if err != nil {
        fmt.Printf("Validation error: %v\n", err)
        return
    }
    
    fmt.Printf("Valid user: %+v\n", validatedUser)
}
Programmatic Struct Validation
package main

import (
    "fmt" 
    "github.com/kaptinlin/gozod"
)

type User struct {
    Name  string `json:"name"`
    Age   int    `json:"age"`
    Email string `json:"email"`
}

func main() {
    // Basic struct validation
    basicSchema := gozod.Struct[User]()
    user := User{Name: "Alice", Age: 25, Email: "alice@example.com"}
    result, err := basicSchema.Parse(user)
    if err == nil {
        fmt.Printf("Basic validation: %+v\n", result)
    }

    // Struct with field validation
    userSchema := gozod.Struct[User](gozod.StructSchema{
        "name":  gozod.String().Min(2).Max(50),
        "age":   gozod.Int().Min(0).Max(120),
        "email": gozod.String().Email(),
    })

    validUser := User{Name: "Bob", Age: 30, Email: "bob@example.com"}
    result, err = userSchema.Parse(validUser)
    if err == nil {
        fmt.Printf("Field validation: %+v\n", result)
    }
}

🚀 Advanced Features

Complete Strict Type Semantics

GoZod uses strict type semantics - no automatic conversions between types:

// Value schemas require exact value types
stringSchema := gozod.String()
result, _ := stringSchema.Parse("hello")     // ✅ string → string
// result, _ := stringSchema.Parse(&str)     // ❌ Error: requires string, got *string

// Pointer schemas require exact pointer types
stringPtrSchema := gozod.StringPtr()
result, _ = stringPtrSchema.Parse(&str)      // ✅ *string → *string
// result, _ = stringPtrSchema.Parse("hello") // ❌ Error: requires *string, got string

// For flexible input handling, use Optional/Nilable modifiers
optionalSchema := gozod.String().Optional()  // Flexible input, *string output
result, _ = optionalSchema.Parse("hello")    // ✅ string → *string (new pointer)
result, _ = optionalSchema.Parse(&str)       // ✅ *string → *string (preserves identity)
Parse vs StrictParse Methods

Choose the right parsing method for your use case:

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

// Parse - Runtime type checking (flexible input)
result, err := schema.Parse("hello")        // ✅ Works with any input type
result, err = schema.Parse(42)              // ❌ Runtime error: invalid type

// StrictParse - Compile-time type safety (optimal performance)
str := "hello"
result, err = schema.StrictParse(str)       // ✅ Compile-time guarantee, optimal performance
// result, err := schema.StrictParse(42)    // ❌ Compile-time error
Custom Validation with Refine

Use .Refine() for custom validation logic:

package main

import (
    "strings"
    "github.com/kaptinlin/gozod"
)

func main() {
    // Custom validation with Refine
    usernameSchema := gozod.String().
        Min(3).
        Max(20).
        Refine(func(username string) bool {
            // Check against blacklist
            blacklist := map[string]bool{"admin": true, "root": true}
            return !blacklist[strings.ToLower(username)]
        }, "Username is not allowed")
    
    // Valid username
    result, err := usernameSchema.Parse("johndoe")  // ✅ Valid
    
    // Invalid username  
    _, err = usernameSchema.Parse("admin")  // ❌ Validation fails
    if err != nil {
        fmt.Printf("Validation failed: %v\n", err)
    }
    
    // Struct validation with custom logic
    type User struct {
        Name  string `gozod:"required,min=2"`
        Email string `gozod:"required,email"`
        Age   int    `gozod:"min=18"`
    }
    
    schema := gozod.FromStruct[User]().Refine(func(user User) bool {
        // Cross-field validation
        return user.Age >= 21 || !strings.Contains(user.Email, "company.com")
    }, "Users under 21 cannot have company emails")
}

### Automatic Circular Reference Handling

GoZod automatically detects and handles circular references:

```go
type User struct {
    Name    string  `gozod:"required,min=2"`
    Email   string  `gozod:"required,email"`
    Friends []*User `gozod:"max=10"`       // Circular reference
}

// No stack overflow - automatically uses lazy evaluation
schema := gozod.FromStruct[User]()

alice := &User{Name: "Alice", Email: "alice@example.com"}
bob := &User{Name: "Bob", Email: "bob@example.com", Friends: []*User{alice}}
alice.Friends = []*User{bob} // Circular reference

result, err := schema.Parse(*alice) // ✅ Handles circular reference safely
Union, Xor, and Intersection Types
// Union types - accepts one of multiple schemas (any match succeeds)
unionSchema := gozod.Union(
    gozod.String(),
    gozod.Int(),
)
result, _ := unionSchema.Parse("hello") // ✅ Matches string
result, _ = unionSchema.Parse(42)       // ✅ Matches int
result, _ = unionSchema.Parse(true)     // ❌ No union member matched

// Xor types - exactly one schema must match (exclusive union)
xorSchema := gozod.Xor([]any{
    gozod.Email(),  // Email format validator
    gozod.URL(),    // URL format validator
})
result, _ = xorSchema.Parse("user@example.com")  // ✅ Matches email only
result, _ = xorSchema.Parse("https://site.com")  // ✅ Matches URL only
result, _ = xorSchema.Parse("invalid")           // ❌ Matches neither

// Intersection types - must satisfy all schemas
intersectionSchema := gozod.Intersection(
    gozod.String().Min(3),              // At least 3 chars
    gozod.String().Max(10),             // At most 10 chars
    gozod.String().RegexString(`^[a-z]+$`), // Only lowercase
)
result, _ = intersectionSchema.Parse("hello")  // ✅ Satisfies all constraints
result, _ = intersectionSchema.Parse("HELLO")  // ❌ Not lowercase

// And/Or methods - fluent composition on any schema type
schema := gozod.String().Min(3).And(gozod.String().Max(10))  // Intersection via method
schema = gozod.Int().Or(gozod.String())                       // Union via method
Performance Optimization with Code Generation

For maximum performance, use code generation:

//go:generate gozodgen

type User struct {
    Name  string `gozod:"required,min=2"`
    Email string `gozod:"required,email"`
    Age   int    `gozod:"required,min=18"`
}

// Generated Schema() method provides zero-reflection validation
func main() {
    schema := gozod.FromStruct[User]() // Uses generated code automatically
    
    user := User{Name: "Alice", Email: "alice@example.com", Age: 25}
    result, err := schema.Parse(user)  // 5-10x faster than reflection
}

🎛️ Comprehensive Type Support

Primitive Types
// Strings with format validation
gozod.String().Min(3).Max(100).Email()
gozod.String().RegexString(`^\d+$`)
gozod.String().Lowercase()  // Validates no uppercase letters
gozod.String().Uppercase()  // Validates no lowercase letters
gozod.String().Normalize()  // Unicode NFC normalization
gozod.Uuid()     // UUID format validator
gozod.Guid()     // GUID format validator (8-4-4-4-12 hex)
gozod.URL()      // URL format validator
gozod.HTTPURL()  // HTTP/HTTPS URL only
gozod.Email()    // Email format validator

// Network formats
gozod.IPv4()     // IPv4: "192.168.1.1"
gozod.IPv6()     // IPv6: "2001:db8::8a2e:370:7334"
gozod.Hostname() // DNS hostname: "example.com"
gozod.MAC()      // MAC address: "00:1A:2B:3C:4D:5E"
gozod.E164()     // E.164 phone: "+14155552671"
gozod.CIDRv4()   // IPv4 CIDR: "192.168.1.0/24"

// Text encodings and hashes
gozod.Hex()      // Hexadecimal string
gozod.Base64()   // Base64 encoding
gozod.JWT()      // JWT token format

// Numbers with range validation  
gozod.Int().Min(0).Max(120).Positive()
gozod.Float64().Min(0.0).Finite()

// Booleans
gozod.Bool()

// Time validation
gozod.Time().After(startDate).Before(endDate)
Complex Types
// Arrays and Slices
gozod.Array(gozod.String()).Min(1).Max(10)
gozod.Slice(gozod.Int()).NonEmpty()

// Tuples - Fixed-length arrays with typed elements
tuple := gozod.Tuple(gozod.String(), gozod.Int(), gozod.Bool())
result, _ := tuple.Parse([]any{"hello", 42, true})

// Tuple with rest element for variadic trailing elements
tupleWithRest := gozod.TupleWithRest(
    []core.ZodSchema{gozod.String(), gozod.Int()},
    gozod.Bool(), // additional elements must be booleans
)

// Maps
gozod.Map(gozod.String()).NonEmpty() // map[string]string, at least one entry
gozod.Map(gozod.Struct[User]()) // map[string]User

// Records with key validation
gozod.Record(gozod.String().Regex(`^[a-z]+$`), gozod.Int()) // lowercase keys only

// LooseRecord - passes through non-matching keys unchanged
gozod.LooseRecord(gozod.String().Regex(`^S_`), gozod.String())

// PartialRecord - allows missing keys for exhaustive key schemas
keys := gozod.Enum("id", "name", "email")
gozod.Record(keys, gozod.String()).Partial() // Missing keys allowed

// Sets - Go idiomatic set pattern with element validation
gozod.Set[string](gozod.String()).Min(1).Max(10) // map[string]struct{}

// Objects (map[string]any)
gozod.Object(gozod.ObjectSchema{
    "name": gozod.String().Min(2),
    "age":  gozod.Int().Min(0),
})
Advanced Types
// Transform types
stringToInt := gozod.String().Regex(`^\d+$`).Transform(
    func(s string, ctx *core.RefinementContext) (any, error) {
        return strconv.Atoi(s)
    },
)

// Lazy types for recursive structures
var nodeSchema gozod.ZodType[Node]
nodeSchema = gozod.Lazy(func() gozod.ZodType[Node] {
    return gozod.Struct[Node](gozod.StructSchema{
        "value":    gozod.String(),
        "children": gozod.Array(nodeSchema), // Self-reference
    })
})

// Schema metadata
schema := gozod.String().Email().Describe("User's primary email")
schema = gozod.Int().Meta(gozod.GlobalMeta{
    Title:       "Age",
    Description: "User's age in years",
})

// Apply - Compose reusable schema modifiers
func addCommonChecks[T types.StringConstraint](s *gozod.ZodString[T]) *gozod.ZodString[T] {
    return s.Min(1).Max(100).Trim()
}
schema := gozod.Apply(gozod.String(), addCommonChecks)

🔧 Error Handling

Comprehensive error information with structured details:

schema := gozod.String().Min(5).Email()
_, err := schema.Parse("hi")

if zodErr, ok := err.(*issues.ZodError); ok {
    // Access structured error information
    for _, issue := range zodErr.Issues {
        fmt.Printf("Path: %v, Code: %s, Message: %s\n", 
            issue.Path, issue.Code, issue.Message)
    }
    
    // Pretty print errors
    fmt.Println(zodErr.PrettifyError())
    
    // Get flattened field errors for forms
    fieldErrors := zodErr.FlattenError()
    for field, errors := range fieldErrors.FieldErrors {
        fmt.Printf("%s: %v\n", field, errors)
    }
}

🏷️ Complete Tag Reference

String Tags
  • required - Field must be present
  • min=N / max=N - Length constraints
  • email / url / uuid - Format validation
  • regex=pattern - Custom regex patterns
Numeric Tags
  • min=N / max=N - Value constraints
  • positive / negative - Sign validation
  • nonnegative / nonpositive - Zero-inclusive constraints
Array Tags
  • min=N / max=N - Element count constraints
  • nonempty - At least one element
  • length=N - Exact element count
Custom Validation

Use .Refine() for custom validation logic on any schema:

schema := gozod.FromStruct[Product]().Refine(func(p Product) bool {
    return strings.HasPrefix(p.SKU, "PROD-")
}, "SKU must start with PROD-")

🌟 Real-World Examples

API Request Validation
type CreateUserRequest struct {
    Name     string   `json:"name" gozod:"required,min=2,max=50"`
    Email    string   `json:"email" gozod:"required,email"`
    Age      int      `json:"age" gozod:"required,min=18,max=120"`
    Tags     []string `json:"tags" gozod:"max=10"`
    Website  string   `json:"website" gozod:"url"`
    IsActive bool     `json:"is_active"`
}

func createUserHandler(w http.ResponseWriter, r *http.Request) {
    var req CreateUserRequest
    if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
        http.Error(w, "Invalid JSON", http.StatusBadRequest)
        return
    }
    
    schema := gozod.FromStruct[CreateUserRequest]()
    validatedReq, err := schema.Parse(req)
    if err != nil {
        writeValidationError(w, err)
        return
    }
    
    user := createUser(validatedReq)
    json.NewEncoder(w).Encode(user)
}
Configuration Validation
type Config struct {
    Environment string `yaml:"environment" validate:"required,regex=^(dev|staging|prod)$"`
    Port        int    `yaml:"port" validate:"required,min=1000,max=9999"`
    Database    struct {
        Host     string `yaml:"host" validate:"required"`
        Port     int    `yaml:"port" validate:"required,min=1,max=65535"`
        Name     string `yaml:"name" validate:"required,min=1"`
        Username string `yaml:"username" validate:"required"`
        Password string `yaml:"password" validate:"required,min=8"`
    } `yaml:"database" validate:"required"`
    Debug bool `yaml:"debug"`
}

func LoadConfig(path string) (*Config, error) {
    data, err := os.ReadFile(path)
    if err != nil {
        return nil, err
    }

    var config Config
    if err := yaml.Unmarshal(data, &config); err != nil {
        return nil, err
    }

    schema := gozod.FromStruct[Config](gozod.WithTagName("validate"))
    return schema.Parse(config)
}

📚 Documentation

OpenAPI 3.1 Support ✅

GoZod schemas generate JSON Schema Draft 2020-12, which is fully compatible with OpenAPI 3.1. Features like nullable types (["string", "null"]), numeric exclusive bounds, conditional schemas (if/then/else), and tuple validation work out of the box. See JSON Schema docs for details.

Note: OpenAPI 3.0 is not supported (use OpenAPI 3.1 instead).

  • Metadata - Schema metadata and introspection capabilities
  • Examples - Working examples for common use cases

🚀 Performance

GoZod is designed for maximum performance:

  • Zero Dependencies - Pure Go implementation
  • Strict Type Semantics - No runtime type conversions
  • StrictParse Method - Compile-time type safety eliminates runtime checks
  • Code Generation - Optional zero-reflection validation (5-10x faster)
  • Efficient Validation Pipeline - Optimized execution paths

🤝 Contributing

We welcome contributions! Please see CONTRIBUTING.md for guidelines.

📄 License

MIT License - see LICENSE for details.

Documentation

Overview

Package gozod provides a TypeScript Zod v4-inspired validation library for Go, offering strongly-typed, zero-dependency 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
)

Issue code constants

Variables

View Source
var (
	SetConfig = core.SetConfig
	Config    = core.Config
)

Global configuration functions

View Source
var (
	String       = types.String
	StringPtr    = types.StringPtr
	Email        = types.Email
	EmailPtr     = types.EmailPtr
	Emoji        = types.Emoji
	EmojiPtr     = types.EmojiPtr
	Base64       = types.Base64
	Base64Ptr    = types.Base64Ptr
	Base64URL    = types.Base64URL
	Base64URLPtr = types.Base64URLPtr
	Hex          = types.Hex
	HexPtr       = types.HexPtr
)

String constructors

View Source
var (
	Bool    = types.Bool
	BoolPtr = types.BoolPtr
)

Boolean constructors

View Source
var (
	Int      = types.Int
	IntPtr   = types.IntPtr
	Int8     = types.Int8
	Int8Ptr  = types.Int8Ptr
	Int16    = types.Int16
	Int16Ptr = types.Int16Ptr
	Int32    = types.Int32
	Int32Ptr = types.Int32Ptr
	Int64    = types.Int64
	Int64Ptr = types.Int64Ptr
)

Integer constructors

View Source
var (
	Uint      = types.Uint
	UintPtr   = types.UintPtr
	Uint8     = types.Uint8
	Uint8Ptr  = types.Uint8Ptr
	Uint16    = types.Uint16
	Uint16Ptr = types.Uint16Ptr
	Uint32    = types.Uint32
	Uint32Ptr = types.Uint32Ptr
	Uint64    = types.Uint64
	Uint64Ptr = types.Uint64Ptr
)

Unsigned integer constructors

View Source
var (
	Float      = types.Float
	FloatPtr   = types.FloatPtr
	Float32    = types.Float32
	Float32Ptr = types.Float32Ptr
	Float64    = types.Float64
	Float64Ptr = types.Float64Ptr
	Number     = types.Number
	NumberPtr  = types.NumberPtr
)

Float constructors

View Source
var (
	BigInt    = types.BigInt
	BigIntPtr = types.BigIntPtr
)

BigInt constructors

View Source
var (
	Complex       = types.Complex
	ComplexPtr    = types.ComplexPtr
	Complex64     = types.Complex64
	Complex64Ptr  = types.Complex64Ptr
	Complex128    = types.Complex128
	Complex128Ptr = types.Complex128Ptr
)

Complex number constructors

View Source
var (
	Time    = types.Time
	TimePtr = types.TimePtr
)

Time constructors

View Source
var (
	IPv4             = types.IPv4
	IPv4Ptr          = types.IPv4Ptr
	IPv6             = types.IPv6
	IPv6Ptr          = types.IPv6Ptr
	CIDRv4           = types.CIDRv4
	CIDRv4Ptr        = types.CIDRv4Ptr
	CIDRv6           = types.CIDRv6
	CIDRv6Ptr        = types.CIDRv6Ptr
	URL              = types.URL
	URLPtr           = types.URLPtr
	Hostname         = types.Hostname
	HostnamePtr      = types.HostnamePtr
	MAC              = types.MAC
	MACPtr           = types.MACPtr
	MACWithDelimiter = types.MACWithDelimiter
	E164             = types.E164
	E164Ptr          = types.E164Ptr
	HTTPURL          = types.HTTPURL
	HTTPURLPtr       = types.HTTPURLPtr
)

Network type constructors

View Source
var (
	Iso            = types.Iso
	IsoPtr         = types.IsoPtr
	IsoDateTime    = types.IsoDateTime
	IsoDateTimePtr = types.IsoDateTimePtr
	IsoDate        = types.IsoDate
	IsoDatePtr     = types.IsoDatePtr
	IsoTime        = types.IsoTime
	IsoTimePtr     = types.IsoTimePtr
	IsoDuration    = types.IsoDuration
	IsoDurationPtr = types.IsoDurationPtr
)

ISO 8601 format constructors

View Source
var (
	PrecisionMinute      = types.PrecisionMinute
	PrecisionSecond      = types.PrecisionSecond
	PrecisionDecisecond  = types.PrecisionDecisecond
	PrecisionCentisecond = types.PrecisionCentisecond
	PrecisionMillisecond = types.PrecisionMillisecond
	PrecisionMicrosecond = types.PrecisionMicrosecond
	PrecisionNanosecond  = types.PrecisionNanosecond
)

ISO precision constants

View Source
var (
	CUID      = types.CUID
	CUIDPtr   = types.CUIDPtr
	CUID2     = types.CUID2
	CUID2Ptr  = types.CUID2Ptr
	GUID      = types.GUID
	GUIDPtr   = types.GUIDPtr
	ULID      = types.ULID
	ULIDPtr   = types.ULIDPtr
	XID       = types.XID
	XIDPtr    = types.XIDPtr
	KSUID     = types.KSUID
	KSUIDPtr  = types.KSUIDPtr
	NanoID    = types.NanoID
	NanoIDPtr = types.NanoIDPtr
	UUID      = types.UUID
	UUIDPtr   = types.UUIDPtr
	UUIDv4    = types.UUIDv4
	UUIDv4Ptr = types.UUIDv4Ptr
	UUIDv6    = types.UUIDv6
	UUIDv6Ptr = types.UUIDv6Ptr
	UUIDv7    = types.UUIDv7
	UUIDv7Ptr = types.UUIDv7Ptr
	JWT       = types.JWT
	JWTPtr    = types.JWTPtr
)

Unique identifier constructors

View Source
var (
	Array    = types.Array
	ArrayPtr = types.ArrayPtr
	Map      = types.Map
	MapPtr   = types.MapPtr
)
View Source
var (
	Tuple         = types.Tuple
	TupleWithRest = types.TupleWithRest
	TuplePtr      = types.TuplePtr
)

Tuple creates a tuple schema with fixed positional items TypeScript Zod v4 equivalent: z.tuple([...])

Usage:

tuple := gozod.Tuple(gozod.String(), gozod.Int())
result, err := tuple.Parse([]any{"hello", 42})
View Source
var (
	LooseRecord    = types.LooseRecord
	LooseRecordPtr = types.LooseRecordPtr
)

LooseRecord creates a record schema that passes through non-matching keys unchanged. Unlike regular Record which errors on keys that don't match the key schema, LooseRecord preserves non-matching keys without validation.

TypeScript Zod v4 equivalent: z.looseRecord(keySchema, valueSchema)

Example:

// Only validate keys starting with "S_"
schema := LooseRecord(String().Regex(`^S_`), String())
result, _ := schema.Parse(map[string]any{"S_name": "John", "other": 123})
// Result: {"S_name": "John", "other": 123} - "other" key is preserved
View Source
var (
	Object          = types.Object
	ObjectPtr       = types.ObjectPtr
	StrictObject    = types.StrictObject
	StrictObjectPtr = types.StrictObjectPtr
	LooseObject     = types.LooseObject
	LooseObjectPtr  = types.LooseObjectPtr
)
View Source
var (
	Union                 = types.Union
	UnionPtr              = types.UnionPtr
	Xor                   = types.Xor
	XorPtr                = types.XorPtr
	XorOf                 = types.XorOf
	Intersection          = types.Intersection
	IntersectionPtr       = types.IntersectionPtr
	DiscriminatedUnion    = types.DiscriminatedUnion
	DiscriminatedUnionPtr = types.DiscriminatedUnionPtr
)

----------------------------------------------------------------------------- Composite Type Constructors -----------------------------------------------------------------------------

View Source
var (
	Any           = types.Any
	AnyPtr        = types.AnyPtr
	Unknown       = types.Unknown
	UnknownPtr    = types.UnknownPtr
	Never         = types.Never
	NeverPtr      = types.NeverPtr
	Nil           = types.Nil
	NilPtr        = types.NilPtr
	File          = types.File
	FilePtr       = types.FilePtr
	Function      = types.Function
	FunctionPtr   = types.FunctionPtr
	StringBool    = types.StringBool
	StringBoolPtr = types.StringBoolPtr
)

----------------------------------------------------------------------------- Special Type Constructors -----------------------------------------------------------------------------

View Source
var (
	LazyAny = types.LazyAny
	LazyPtr = types.LazyPtr
)
View Source
var (
	TreeifyError  = issues.TreeifyError
	PrettifyError = issues.PrettifyError
	FlattenError  = issues.FlattenError
	FormatError   = issues.FormatError
)

Re-export TypeScript Zod v4 compatible error formatting functions so that callers can perform common error transformations without depending on the internal package path. These functions match TypeScript Zod's API patterns: z.treeifyError(), z.prettifyError(), z.flattenError()

View Source
var (
	TreeifyErrorWithMapper     = issues.TreeifyErrorWithMapper
	PrettifyErrorWithFormatter = issues.PrettifyErrorWithFormatter
	FlattenErrorWithMapper     = issues.FlattenErrorWithMapper
	FlattenErrorWithFormatter  = issues.FlattenErrorWithFormatter
)

Advanced error formatting functions with custom mappers - these provide additional flexibility while maintaining TypeScript Zod v4 compatibility

View Source
var (
	ToDotPath       = utils.ToDotPath
	FormatErrorPath = utils.FormatErrorPath
)
View Source
var (
	// ToJSONSchema errors
	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
	ErrMapNoMethods                  = jsonschema.ErrMapNoMethods
	ErrMapKeyNotSchema               = jsonschema.ErrMapKeyNotSchema
	ErrMapValueNotSchema             = jsonschema.ErrMapValueNotSchema

	// FromJSONSchema errors
	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
)

JSON Schema conversion error variables re-exported for convenience.

View Source
var Describe = checks.Describe

Describe creates a check that registers a description in the global registry. This is a no-op validation check that only attaches metadata when the check is added to a schema.

TypeScript Zod v4 equivalent: z.describe(description)

Example:

schema := gozod.String().Check(gozod.Describe("User email address"))
meta, _ := gozod.GlobalRegistry.Get(schema)
// meta.Description == "User email address"
View Source
var FromJSONSchema = jsonschema.FromJSONSchema

FromJSONSchema converts a kaptinlin/jsonschema Schema to a GoZod schema.

Example:

jsonSchema := &lib.Schema{Type: []string{"string"}}
zodSchema, err := gozod.FromJSONSchema(jsonSchema)
View Source
var GlobalRegistry = core.GlobalRegistry

GlobalRegistry is the framework-provided, process-wide registry instance. Use it to store shared metadata that should be accessible throughout your application.

View Source
var IsZodError = issues.IsZodError

IsZodError checks whether an error is a ZodError.

View Source
var Meta = checks.Meta

Meta creates a check that registers metadata in the global registry. This is a no-op validation check that only attaches metadata when the check is added to a schema.

TypeScript Zod v4 equivalent: z.meta(metadata)

Example:

schema := gozod.Number().Check(gozod.Meta(gozod.GlobalMeta{
    Title: "Age",
    Description: "User's age in years",
}))
meta, _ := gozod.GlobalRegistry.Get(schema)
// meta.Title == "Age"
// meta.Description == "User's age in years"
View Source
var ToJSONSchema = jsonschema.ToJSONSchema

ToJSONSchema converts a GoZod schema or registry into a JSON Schema instance.

TypeScript Zod v4 equivalent: zodToJsonSchema(schema)

Example:

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

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. It takes a schema and a function that receives the schema and returns a potentially different schema type. This enables modular composition of common validation patterns.

TypeScript Zod v4 equivalent: schema.apply(fn) In Go, this is a standalone generic function due to language constraints.

Example:

// Define a reusable modifier
func addCommonStringChecks[T types.StringConstraint](s *gozod.ZodString[T]) *gozod.ZodString[T] {
    return s.Min(1).Max(100).Trim()
}

// Apply it to a schema
schema := gozod.Apply(gozod.String(), addCommonStringChecks)

// Chain with other modifiers
optionalSchema := gozod.Apply(gozod.String(), addCommonStringChecks).Optional()

func FromStruct added in v0.5.0

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

FromStruct creates a ZodStruct schema from struct tags This provides convenient tag-based validation for Go structs

Example:

type User struct {
    Name  string `gozod:"required,min=2,max=50"`
    Email string `gozod:"required,email"`
}

schema := gozod.FromStruct[User]()

Use WithTagName to customize the tag name:

schema := gozod.FromStruct[User](gozod.WithTagName("validate"))

func FromStructPtr added in v0.5.0

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

FromStructPtr creates a ZodStruct schema for pointer types from struct tags This is useful for handling optional/nullable struct inputs

func Lazy

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

Types

type CheckParams added in v0.3.0

type CheckParams = core.CheckParams

Validation check aliases

type CustomParams added in v0.3.1

type CustomParams = core.CustomParams

Validation check aliases

type FlattenedError

type FlattenedError = issues.FlattenedError

type FromJSONSchemaOptions added in v0.5.4

type FromJSONSchemaOptions = jsonschema.FromJSONSchemaOptions

FromJSONSchemaOptions configures the FromJSONSchema conversion. Re-exported from jsonschema subpackage for convenience.

type FromStructOption added in v0.8.0

type FromStructOption = types.FromStructOption

FromStructOption configures FromStruct behavior

func WithTagName added in v0.8.0

func WithTagName(name string) FromStructOption

WithTagName sets a custom tag name (default: "gozod")

Example:

type User struct {
    Name string `validate:"required,min=2"`
}

schema := gozod.FromStruct[User](gozod.WithTagName("validate"))

type GlobalMeta added in v0.3.1

type GlobalMeta = core.GlobalMeta

GlobalMeta mirrors common JSON-Schema keys and serves as a convenient default metadata structure. Alias to core.GlobalMeta so callers don't need to import the core package.

type IsoDatetimeOptions added in v0.3.0

type IsoDatetimeOptions = types.IsoDatetimeOptions

----------------------------------------------------------------------------- String Format Types -----------------------------------------------------------------------------

type IsoTimeOptions added in v0.3.0

type IsoTimeOptions = types.IsoTimeOptions

----------------------------------------------------------------------------- String Format Types -----------------------------------------------------------------------------

type IssueCode

type IssueCode = core.IssueCode

Validation payload and issue code aliases

type JSONSchemaOptions added in v0.3.1

type JSONSchemaOptions = jsonschema.Options

JSONSchemaOptions configures the ToJSONSchema conversion. Re-exported from jsonschema subpackage for convenience.

type JWTOptions added in v0.3.0

type JWTOptions = types.JWTOptions

----------------------------------------------------------------------------- String Format Types -----------------------------------------------------------------------------

type MessageFormatter added in v0.3.0

type MessageFormatter = issues.MessageFormatter

type ObjectSchema

type ObjectSchema = core.ObjectSchema

Schema and configuration aliases

type OverrideContext added in v0.3.1

type OverrideContext = jsonschema.OverrideContext

OverrideContext provides context for the Override function in JSON Schema conversion. Re-exported from jsonschema subpackage for convenience.

type ParsePayload

type ParsePayload = core.ParsePayload

Validation payload and issue code aliases

type Registry added in v0.3.1

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

Registry provides a lightweight, type-safe store for attaching metadata to any Schema. This is an alias to core.Registry to make the API available via the primary gozod package.

Example:

fieldReg := gozod.NewRegistry[FieldMeta]()
fieldReg.Add(nameSchema, FieldMeta{Title: "User Name"})

See docs/metadata.md for usage patterns and best practices.

func NewRegistry added in v0.3.1

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

NewRegistry creates an empty Registry. It's a thin wrapper around core.NewRegistry to expose the constructor at the root package level.

type SchemaParams

type SchemaParams = core.SchemaParams

Schema and configuration aliases

type StructSchema added in v0.2.0

type StructSchema = core.StructSchema

Schema and configuration aliases

type URLOptions added in v0.3.0

type URLOptions = types.URLOptions

----------------------------------------------------------------------------- String Format Types -----------------------------------------------------------------------------

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]

----------------------------------------------------------------------------- Special Types -----------------------------------------------------------------------------

type ZodArray

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

----------------------------------------------------------------------------- Collection Types -----------------------------------------------------------------------------

type ZodBase64 added in v0.3.0

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

----------------------------------------------------------------------------- String Format Types -----------------------------------------------------------------------------

type ZodBase64URL added in v0.3.0

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

----------------------------------------------------------------------------- String Format Types -----------------------------------------------------------------------------

type ZodBool

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

----------------------------------------------------------------------------- Primitive Types -----------------------------------------------------------------------------

type ZodCIDRv4

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

----------------------------------------------------------------------------- String Format Types -----------------------------------------------------------------------------

type ZodCIDRv6

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

----------------------------------------------------------------------------- String Format Types -----------------------------------------------------------------------------

type ZodCUID added in v0.3.0

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

ZodCUID validates CUID strings.

type ZodCUID2 added in v0.3.0

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

----------------------------------------------------------------------------- String Format Types -----------------------------------------------------------------------------

type ZodCheck

type ZodCheck = core.ZodCheck

Validation check aliases

type ZodCheckDef

type ZodCheckDef = core.ZodCheckDef

Validation check aliases

type ZodCheckFn

type ZodCheckFn = core.ZodCheckFn

Validation check aliases

type ZodCheckInternals

type ZodCheckInternals = core.ZodCheckInternals

Validation check aliases

type ZodComplex

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

----------------------------------------------------------------------------- Primitive Types -----------------------------------------------------------------------------

type ZodConfig

type ZodConfig = core.ZodConfig

Schema and configuration aliases

type ZodDiscriminatedUnion

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

----------------------------------------------------------------------------- Composite Types -----------------------------------------------------------------------------

type ZodE164 added in v0.5.4

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

----------------------------------------------------------------------------- String Format Types -----------------------------------------------------------------------------

type ZodEmail added in v0.3.0

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

ZodEmail validates email addresses.

type ZodEmoji added in v0.3.0

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

----------------------------------------------------------------------------- String Format Types -----------------------------------------------------------------------------

type ZodEnum

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

----------------------------------------------------------------------------- Special Types -----------------------------------------------------------------------------

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

Error type aliases

type ZodErrorTree

type ZodErrorTree = issues.ZodErrorTree

type ZodFile

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

----------------------------------------------------------------------------- Special Types -----------------------------------------------------------------------------

type ZodFloat

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

----------------------------------------------------------------------------- Primitive Types -----------------------------------------------------------------------------

type ZodFormattedError

type ZodFormattedError = issues.ZodFormattedError

type ZodFunction

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

----------------------------------------------------------------------------- Special Types -----------------------------------------------------------------------------

type ZodGUID added in v0.5.5

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

----------------------------------------------------------------------------- String Format Types -----------------------------------------------------------------------------

type ZodHex added in v0.5.4

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

----------------------------------------------------------------------------- String Format Types -----------------------------------------------------------------------------

type ZodHostname added in v0.5.4

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

----------------------------------------------------------------------------- String Format Types -----------------------------------------------------------------------------

type ZodIPv4

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

ZodIPv4 validates IPv4 addresses.

type ZodIPv6

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

----------------------------------------------------------------------------- String Format Types -----------------------------------------------------------------------------

type ZodInteger

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

----------------------------------------------------------------------------- Primitive Types -----------------------------------------------------------------------------

type ZodIntersection

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

----------------------------------------------------------------------------- Composite Types -----------------------------------------------------------------------------

type ZodIso added in v0.3.0

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

ZodIso validates ISO 8601 formatted strings.

type ZodIssue

type ZodIssue = core.ZodIssue

Error type aliases

type ZodJWT added in v0.3.0

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

----------------------------------------------------------------------------- String Format Types -----------------------------------------------------------------------------

type ZodKSUID added in v0.3.0

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

----------------------------------------------------------------------------- String Format Types -----------------------------------------------------------------------------

type ZodLazy

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

----------------------------------------------------------------------------- Special Types -----------------------------------------------------------------------------

type ZodLiteral

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

----------------------------------------------------------------------------- Special Types -----------------------------------------------------------------------------

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]

----------------------------------------------------------------------------- String Format Types -----------------------------------------------------------------------------

type ZodMap

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

----------------------------------------------------------------------------- Collection Types -----------------------------------------------------------------------------

type ZodNanoID added in v0.3.0

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

----------------------------------------------------------------------------- String Format Types -----------------------------------------------------------------------------

type ZodNever

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

----------------------------------------------------------------------------- Special Types -----------------------------------------------------------------------------

type ZodNil

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

----------------------------------------------------------------------------- Special Types -----------------------------------------------------------------------------

type ZodObject

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

----------------------------------------------------------------------------- Collection Types -----------------------------------------------------------------------------

type ZodRawIssue

type ZodRawIssue = core.ZodRawIssue

Error type aliases

type ZodRecord

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

----------------------------------------------------------------------------- Collection Types -----------------------------------------------------------------------------

func Record

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

Record creates a record schema with the specified key schema and value schema. Example: Record(String(), Int()) parses map[string]int.

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]

RecordPtr is the pointer-returning counterpart of Record.

type ZodRefineFn added in v0.3.0

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

Validation check aliases

type ZodSet added in v0.5.5

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

----------------------------------------------------------------------------- Collection Types -----------------------------------------------------------------------------

func Set added in v0.5.5

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

Set creates a set schema with element validation (returns value constraint). In Go, sets are represented as map[T]struct{} where T must be comparable. TypeScript Zod v4 equivalent: z.set(schema)

Example:

schema := Set[string](String())
result, _ := schema.Parse(map[string]struct{}{"a": {}, "b": {}})

func SetPtr added in v0.5.5

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

SetPtr creates a set schema with pointer constraint (returns pointer constraint).

type ZodSlice

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

----------------------------------------------------------------------------- Collection Types -----------------------------------------------------------------------------

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]

----------------------------------------------------------------------------- Primitive Types -----------------------------------------------------------------------------

type ZodStringBool

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

----------------------------------------------------------------------------- Special Types -----------------------------------------------------------------------------

type ZodStruct

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

----------------------------------------------------------------------------- Collection Types -----------------------------------------------------------------------------

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]

----------------------------------------------------------------------------- Primitive Types -----------------------------------------------------------------------------

type ZodTuple added in v0.5.4

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

----------------------------------------------------------------------------- Collection Types -----------------------------------------------------------------------------

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]

----------------------------------------------------------------------------- String Format Types -----------------------------------------------------------------------------

type ZodURL added in v0.3.0

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

----------------------------------------------------------------------------- String Format Types -----------------------------------------------------------------------------

type ZodUUID added in v0.3.0

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

----------------------------------------------------------------------------- String Format Types -----------------------------------------------------------------------------

type ZodUnion

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

----------------------------------------------------------------------------- Composite Types -----------------------------------------------------------------------------

type ZodUnknown

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

----------------------------------------------------------------------------- Special Types -----------------------------------------------------------------------------

type ZodWhenFn

type ZodWhenFn = core.ZodWhenFn

Validation check aliases

type ZodXID added in v0.3.0

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

----------------------------------------------------------------------------- String Format Types -----------------------------------------------------------------------------

Directories

Path Synopsis
cmd
gozodgen command
Package main implements the gozodgen code generation tool.
Package main implements the gozodgen code generation tool.
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 GoZod code generation for zero-overhead struct tag validation.
Package main demonstrates GoZod code generation for zero-overhead struct tag validation.
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
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 provides shared tag parsing functionality for GoZod.
Package tagparser provides shared tag parsing functionality for GoZod.
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 all validation types supported by gozod, with one type per file following a consistent structure.
Package types provides public schema implementations for all validation types supported by gozod, with one type per file following a consistent structure.

Jump to

Keyboard shortcuts

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