Documentation
¶
Overview ¶
Package core contains the low-level building blocks shared by every schema implementation. This file groups **validation check** primitives: the interfaces, configuration objects and function signatures required to plug additional constraints into any Zod schema.
Naming convention
ZodCheck* – general check abstractions (interface / internals / def) ZodCheckFn – validation function executed at runtime ZodWhenFn – predicate that decides whether the check should run ZodRefineFn – type-safe helper for simple boolean refinements
A *check* is therefore a self-contained unit composed of metadata + execution function. Higher-level packages (`internal/checks`, individual type packages, …) create concrete checks by embedding / configuring these primitives.
Index ¶
- Variables
- type CheckParams
- type Cloneable
- type CustomParams
- type GlobalMeta
- type IssueCode
- type ObjectSchema
- type ParseContext
- type ParseParams
- type ParsePayload
- func (p *ParsePayload) AddIssue(issue ZodRawIssue)
- func (p *ParsePayload) AddIssueWithCode(code IssueCode, message string)
- func (p *ParsePayload) AddIssueWithMessage(message string)
- func (p *ParsePayload) AddIssueWithPath(issue ZodRawIssue, path []any)
- func (p *ParsePayload) AddIssues(issues ...ZodRawIssue)
- func (p *ParsePayload) Clone() *ParsePayload
- func (p *ParsePayload) GetIssueCount() int
- func (p *ParsePayload) GetIssues() []ZodRawIssue
- func (p *ParsePayload) GetPath() []any
- func (p *ParsePayload) GetPathString() string
- func (p *ParsePayload) GetValue() any
- func (p *ParsePayload) HasIssues() bool
- func (p *ParsePayload) PushPath(element any)
- func (p *ParsePayload) SetIssues(issues []ZodRawIssue)
- func (p *ParsePayload) SetValue(v any)
- func (p *ParsePayload) WithCleanIssues() *ParsePayload
- type ParsedType
- type RefinementContext
- type Registry
- type SchemaParams
- type StructSchema
- type ZodCheck
- type ZodCheckDef
- type ZodCheckFn
- type ZodCheckInternals
- type ZodConfig
- type ZodCustomParams
- type ZodErrorMap
- type ZodIssue
- func (z ZodIssue) Error() string
- func (i ZodIssue) GetDivisor() (any, bool)
- func (i ZodIssue) GetExpected() (ZodTypeCode, bool)
- func (i ZodIssue) GetFormat() (string, bool)
- func (z *ZodIssue) GetMaximum() (any, bool)
- func (z *ZodIssue) GetMinimum() (any, bool)
- func (i ZodIssue) GetReceived() (ZodTypeCode, bool)
- func (z ZodIssue) String() string
- type ZodIssueBase
- type ZodIssueInvalidType
- type ZodIssueInvalidValue
- type ZodPipe
- func (z *ZodPipe[In, Out]) GetInner() ZodSchema
- func (z *ZodPipe[In, Out]) GetInternals() *ZodTypeInternals
- func (z *ZodPipe[In, Out]) GetOutput() ZodSchema
- func (z *ZodPipe[In, Out]) IsNilable() bool
- func (z *ZodPipe[In, Out]) IsOptional() bool
- func (z *ZodPipe[In, Out]) MustParse(input any, ctx ...*ParseContext) Out
- func (z *ZodPipe[In, Out]) Parse(input any, ctx ...*ParseContext) (Out, error)
- func (z *ZodPipe[In, Middle]) Pipe(target ZodType[any]) *ZodPipe[Middle, any]
- func (z *ZodPipe[In, Middle]) Transform(fn func(Middle, *RefinementContext) (any, error)) *ZodTransform[Middle, any]
- type ZodRawIssue
- func (r ZodRawIssue) GetDivisor() any
- func (r ZodRawIssue) GetExpected() ZodTypeCode
- func (r ZodRawIssue) GetFormat() string
- func (r ZodRawIssue) GetIncludes() string
- func (r ZodRawIssue) GetInclusive() bool
- func (r ZodRawIssue) GetKeys() []string
- func (r ZodRawIssue) GetMaximum() any
- func (r ZodRawIssue) GetMinimum() any
- func (r ZodRawIssue) GetOrigin() string
- func (r ZodRawIssue) GetPattern() string
- func (r ZodRawIssue) GetPrefix() string
- func (r ZodRawIssue) GetReceived() ZodTypeCode
- func (r ZodRawIssue) GetSuffix() string
- func (r ZodRawIssue) GetValues() []any
- type ZodRefineFn
- type ZodSchema
- type ZodTransform
- func (z *ZodTransform[In, Out]) GetInner() ZodSchema
- func (z *ZodTransform[In, Out]) GetInternals() *ZodTypeInternals
- func (z *ZodTransform[In, Out]) IsNilable() bool
- func (z *ZodTransform[In, Out]) IsOptional() bool
- func (z *ZodTransform[In, Out]) MustParse(input any, ctx ...*ParseContext) Out
- func (z *ZodTransform[In, Out]) Parse(input any, ctx ...*ParseContext) (Out, error)
- func (z *ZodTransform[In, Out]) ParseAny(input any, ctx ...*ParseContext) (any, error)
- func (z *ZodTransform[In, Middle]) Pipe(target ZodType[any]) *ZodPipe[Middle, any]
- func (z *ZodTransform[In, Middle]) Transform(fn func(Middle, *RefinementContext) (any, error)) *ZodTransform[Middle, any]
- type ZodType
- type ZodTypeCode
- type ZodTypeDef
- type ZodTypeInternals
- func (z *ZodTypeInternals) AddCheck(check ZodCheck)
- func (z *ZodTypeInternals) Clone() *ZodTypeInternals
- func (z *ZodTypeInternals) IsCoerce() bool
- func (z *ZodTypeInternals) IsExactOptional() bool
- func (z *ZodTypeInternals) IsNilable() bool
- func (z *ZodTypeInternals) IsNonOptional() bool
- func (z *ZodTypeInternals) IsOptional() bool
- func (z *ZodTypeInternals) SetCoerce(value bool)
- func (z *ZodTypeInternals) SetDefaultFunc(fn func() any)
- func (z *ZodTypeInternals) SetDefaultValue(value any)
- func (z *ZodTypeInternals) SetExactOptional(value bool)
- func (z *ZodTypeInternals) SetNilable(value bool)
- func (z *ZodTypeInternals) SetNonOptional(value bool)
- func (z *ZodTypeInternals) SetOptional(value bool)
- func (z *ZodTypeInternals) SetPrefaultFunc(fn func() any)
- func (z *ZodTypeInternals) SetPrefaultValue(value any)
- func (z *ZodTypeInternals) SetTransform(fn func(any, *RefinementContext) (any, error))
- type ZodWhenFn
Constants ¶
This section is empty.
Variables ¶
var (
ErrInvalidTransformType = errors.New("invalid type for transform")
)
Static error variables
var (
ErrSchemaNotZodSchema = fmt.Errorf("schema does not implement ZodSchema interface")
)
Static error variables to comply with err113
var GlobalRegistry = NewRegistry[GlobalMeta]()
GlobalRegistry is the default, framework-provided global registry for convenient, shared metadata collection.
Functions ¶
This section is empty.
Types ¶
type CheckParams ¶ added in v0.3.0
type CheckParams struct {
Error string // Custom error message.
}
CheckParams defines the parameters for attaching a validation check. This is a simplified version of SchemaParams for check-specific configuration.
type Cloneable ¶
type Cloneable interface {
// CloneFrom copies configuration and state from a source schema instance.
// The source should be of the same concrete type.
CloneFrom(source any)
}
Cloneable is an optional interface for schemas that need to support deep-copying of their internal state. This is essential for modifiers like `.Optional()` or `.Transform()` that create new schema instances without modifying the original.
type CustomParams ¶ added in v0.3.1
type CustomParams struct {
Error any `json:"error,omitempty"` // Custom error message or error map
Abort bool `json:"abort,omitempty"` // Stop validation on failure (default: false for refine)
Path []any `json:"path,omitempty"` // Custom error path
When ZodWhenFn `json:"-"` // Conditional execution predicate
Params map[string]any `json:"params,omitempty"` // Additional parameters
}
CustomParams represents parameters for custom validation checks. Corresponds to TypeScript's $ZodCustomParams, providing full configuration for refinement operations including error handling, execution control, and conditional logic.
type GlobalMeta ¶ added in v0.3.1
type GlobalMeta struct {
ID string `json:"id,omitempty"`
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
Examples []any `json:"examples,omitempty"`
}
GlobalMeta defines a standard, optional metadata structure that aligns with common JSON Schema fields. Users can extend this for their own purposes.
type IssueCode ¶
type IssueCode string
IssueCode represents validation issue types These codes categorize different types of validation failures
const ( // Type validation issues InvalidType IssueCode = "invalid_type" // Input type doesn't match expected type InvalidValue IssueCode = "invalid_value" // Input value not in allowed set InvalidFormat IssueCode = "invalid_format" // String doesn't match expected format InvalidUnion IssueCode = "invalid_union" // None of union alternatives match InvalidKey IssueCode = "invalid_key" // Object key validation failed InvalidElement IssueCode = "invalid_element" // Array element validation failed // Range validation issues TooBig IssueCode = "too_big" // Value exceeds maximum limit TooSmall IssueCode = "too_small" // Value below minimum limit NotMultipleOf IssueCode = "not_multiple_of" // Value not multiple of divisor // Structure validation issues UnrecognizedKeys IssueCode = "unrecognized_keys" // Object has unknown keys // Custom validation issues Custom IssueCode = "custom" // Custom validation failure // Schema validation issues InvalidSchema IssueCode = "invalid_schema" // Schema definition is invalid // Discriminator validation issues InvalidDiscriminator IssueCode = "invalid_discriminator" // Discriminator field missing/invalid // Intersection validation issues IncompatibleTypes IssueCode = "incompatible_types" // Types cannot be merged (intersection) // New validation issues MissingRequired IssueCode = "missing_required" // Required field is missing TypeConversion IssueCode = "type_conversion" // Type conversion failed NilPointer IssueCode = "nil_pointer" // Nil pointer encountered )
type ObjectSchema ¶
ObjectSchema defines the shape of an object for validation. It maps field names to their corresponding validation schemas.
type ParseContext ¶
type ParseContext struct {
// Error customizes error messages during validation.
// When provided, this function will be called to generate custom error messages.
Error ZodErrorMap
// ReportInput includes the input field in issue objects.
// When true, validation issues will include the original input value.
ReportInput bool
// IsPrefaultContext indicates if this parsing is for a prefault value
// When true, validators should allow prefault values to proceed to refinement
IsPrefaultContext bool
}
ParseContext contains the full configuration and state for a validation run. It is passed through the validation pipeline.
func NewParseContext ¶
func NewParseContext() *ParseContext
NewParseContext creates a new parse context with default values
func (*ParseContext) Clone ¶
func (ctx *ParseContext) Clone() *ParseContext
Clone creates a copy of the parse context
func (*ParseContext) WithCustomError ¶
func (ctx *ParseContext) WithCustomError(errorMap ZodErrorMap) *ParseContext
WithCustomError creates a new context with a custom error mapping function
func (*ParseContext) WithReportInput ¶
func (ctx *ParseContext) WithReportInput(report bool) *ParseContext
WithReportInput creates a new context with input reporting enabled/disabled
type ParseParams ¶
type ParseParams struct {
Error ZodErrorMap // Per-parse error customization
ReportInput bool // Whether to include input in errors
}
ParseParams represents parameters for a single parse-time configuration. It allows overriding global or schema-level settings for one validation run.
type ParsePayload ¶
type ParsePayload struct {
// contains filtered or unexported fields
}
ParsePayload contains the value and validation issues during parsing. This structure is passed through the validation pipeline to collect results.
func NewParsePayload ¶
func NewParsePayload(value any) *ParsePayload
NewParsePayload creates a new parsing payload with given value
func NewParsePayloadWithPath ¶
func NewParsePayloadWithPath(value any, path []any) *ParsePayload
NewParsePayloadWithPath creates a new parsing payload with value and path
func (*ParsePayload) AddIssue ¶
func (p *ParsePayload) AddIssue(issue ZodRawIssue)
AddIssue adds a validation issue to the payload
func (*ParsePayload) AddIssueWithCode ¶ added in v0.3.0
func (p *ParsePayload) AddIssueWithCode(code IssueCode, message string)
AddIssueWithCode adds an issue with the specified IssueCode and message.
func (*ParsePayload) AddIssueWithMessage ¶ added in v0.3.0
func (p *ParsePayload) AddIssueWithMessage(message string)
AddIssueWithMessage adds a custom issue with the provided message using IssueCode Custom.
func (*ParsePayload) AddIssueWithPath ¶
func (p *ParsePayload) AddIssueWithPath(issue ZodRawIssue, path []any)
AddIssueWithPath adds a validation issue with a specific path override
func (*ParsePayload) AddIssues ¶ added in v0.3.0
func (p *ParsePayload) AddIssues(issues ...ZodRawIssue)
AddIssues adds multiple issues to the payload
func (*ParsePayload) Clone ¶
func (p *ParsePayload) Clone() *ParsePayload
Clone creates a deep copy of the payload
func (*ParsePayload) GetIssueCount ¶
func (p *ParsePayload) GetIssueCount() int
GetIssueCount returns the number of validation issues
func (*ParsePayload) GetIssues ¶ added in v0.2.4
func (p *ParsePayload) GetIssues() []ZodRawIssue
GetIssues returns a copy of the current validation issues
func (*ParsePayload) GetPath ¶
func (p *ParsePayload) GetPath() []any
GetPath returns a copy of the current validation path
func (*ParsePayload) GetPathString ¶
func (p *ParsePayload) GetPathString() string
GetPathString returns a string representation of the current path
func (*ParsePayload) GetValue ¶ added in v0.2.4
func (p *ParsePayload) GetValue() any
GetValue returns the current value being validated
func (*ParsePayload) HasIssues ¶
func (p *ParsePayload) HasIssues() bool
HasIssues checks if the payload has any validation issues
func (*ParsePayload) PushPath ¶
func (p *ParsePayload) PushPath(element any)
PushPath adds a path element to the current validation path
func (*ParsePayload) SetIssues ¶ added in v0.2.4
func (p *ParsePayload) SetIssues(issues []ZodRawIssue)
SetIssues replaces the issues slice with a new one
func (*ParsePayload) SetValue ¶ added in v0.2.4
func (p *ParsePayload) SetValue(v any)
SetValue assigns a new value to the payload.
func (*ParsePayload) WithCleanIssues ¶
func (p *ParsePayload) WithCleanIssues() *ParsePayload
WithCleanIssues creates a new payload with same value and path but no issues
type ParsedType ¶
type ParsedType string
ParsedType represents the type of parsed data values at runtime This corresponds to Zod v4's ParsedTypes See: .reference/zod/packages/zod/src/v4/core/util.ts:66-82 These are used during runtime type detection and validation
const ( ParsedTypeString ParsedType = "string" // String data type ParsedTypeNumber ParsedType = "number" // Numeric data type (integers) ParsedTypeBigint ParsedType = "bigint" // Big integer data type ParsedTypeBool ParsedType = "bool" // Boolean data type ParsedTypeFloat ParsedType = "float" // Floating-point data type ParsedTypeObject ParsedType = "object" // Object/struct data type ParsedTypeFunction ParsedType = "function" // Function data type ParsedTypeFile ParsedType = "file" // File data type ParsedTypeDate ParsedType = "date" // Date/time data type ParsedTypeArray ParsedType = "array" // Fixed-size array data type ParsedTypeSlice ParsedType = "slice" // Dynamic slice data type ParsedTypeTuple ParsedType = "tuple" // Fixed-length tuple data type ParsedTypeMap ParsedType = "map" // Map data type ParsedTypeSet ParsedType = "set" // Set data type (map[T]struct{}) ParsedTypeNaN ParsedType = "nan" // Not-a-Number data type ParsedTypeNil ParsedType = "nil" // Nil/null data type ParsedTypeComplex ParsedType = "complex" // Complex number data type ParsedTypeStruct ParsedType = "struct" // Go struct data type ParsedTypeEnum ParsedType = "enum" // Enumeration data type ParsedTypeUnknown ParsedType = "unknown" // Unknown data type )
type RefinementContext ¶
type RefinementContext struct {
*ParseContext // Embeds the base parse context
Value any // The value being refined/transformed
AddIssue func(issue ZodIssue) // Function to add validation issues
}
RefinementContext provides context for refinement and transformation operations. It is passed to the user-provided function in `.transform()`.
type Registry ¶ added in v0.3.1
type Registry[M any] struct { // contains filtered or unexported fields }
Registry provides a lightweight implementation to associate arbitrary, strongly-typed metadata with any `ZodSchema` instance. The API is intentionally minimal—only the most common CRUD operations are included.
Requirements & Design Notes:
- M must be a comparable type (basic types, structs, interfaces, etc.).
- The implementation relies on a `map[ZodSchema]M`. This works because every built-in GoZod schema is a pointer and therefore comparable.
- The Registry is concurrency-safe; read and write operations are guarded by an RWMutex. If you need advanced features (filtering, cloning, etc.), you can compose them on top of this implementation.
- The design mirrors the TypeScript Zod Registry feature but remains a strict subset—no over-engineering or extra capabilities that don't exist in the original TS API (e.g., no named registries).
func NewRegistry ¶ added in v0.3.1
NewRegistry creates an empty Registry.
func (*Registry[M]) Add ¶ added in v0.3.1
Add associates a schema with metadata; it overwrites the entry if it already exists. Returns the Registry to allow for method chaining.
func (*Registry[M]) Get ¶ added in v0.3.1
Get retrieves the metadata for a schema and reports whether it was found.
type SchemaParams ¶
type SchemaParams struct {
Error any // Error message or error map (string or ZodErrorMap)
Description string // Human-readable description
Abort bool // Abort on first validation failure
Params map[string]any // Additional extensible parameters
}
SchemaParams contains optional parameters for schema creation and check attachment. It provides a flexible way to configure schemas with error messages, descriptions, and other extensible options.
func WithAbort ¶ added in v0.3.0
func WithAbort() SchemaParams
WithAbort creates a SchemaParams with abort-on-error enabled.
func WithDescription ¶ added in v0.3.0
func WithDescription(description string) SchemaParams
WithDescription creates a SchemaParams with a description.
func WithError ¶ added in v0.3.0
func WithError(message string) SchemaParams
WithError creates a SchemaParams with a custom error message.
type StructSchema ¶
StructSchema defines the shape of a struct for validation. It maps field names to their corresponding validation schemas.
type ZodCheck ¶
type ZodCheck interface {
GetZod() *ZodCheckInternals
}
ZodCheck represents the interface for any validation constraint. All checks (e.g., min length, regex) must implement this interface to be attached to a schema.
type ZodCheckDef ¶
type ZodCheckDef struct {
Check string // The unique identifier for the check (e.g., "min_length").
Error *ZodErrorMap // An optional custom error mapping function.
Abort bool // If true, parsing aborts if this check fails.
}
ZodCheckDef defines the static configuration for a validation check. Contains the basic configuration for any validation check
type ZodCheckFn ¶
type ZodCheckFn func(payload *ParsePayload)
ZodCheckFn defines the signature for a validation execution function. This function performs the actual validation logic on a ParsePayload.
type ZodCheckInternals ¶
type ZodCheckInternals struct {
Def *ZodCheckDef // The check's definition and metadata.
Issc *ZodIssueBase // A template for issues this check might create.
Check ZodCheckFn // The validation function to execute.
OnAttach []func(schema any) // Callbacks executed when the check is attached to a schema.
When func(payload *ParsePayload) bool // A predicate to conditionally run the check.
}
ZodCheckInternals contains the internal state and logic for a check. This structure holds all the necessary data for executing a validation check
func (*ZodCheckInternals) GetZod ¶
func (c *ZodCheckInternals) GetZod() *ZodCheckInternals
GetZod implements the ZodCheck interface. Returns the internal structure itself following TypeScript pattern
type ZodConfig ¶
type ZodConfig struct {
CustomError ZodErrorMap
LocaleError ZodErrorMap
}
ZodConfig represents global configuration for validation and error handling
func GetConfig ¶
func GetConfig() *ZodConfig
GetConfig returns a read-only copy of the current global configuration
func (*ZodConfig) GetCustomError ¶
func (c *ZodConfig) GetCustomError() ZodErrorMap
GetCustomError returns the custom error map from ZodConfig
func (*ZodConfig) GetLocaleError ¶
func (c *ZodConfig) GetLocaleError() ZodErrorMap
GetLocaleError returns the locale error map from ZodConfig
type ZodCustomParams ¶ added in v0.3.1
type ZodCustomParams = CustomParams
ZodCustomParams is a type alias for CustomParams to maintain consistency with TypeScript naming conventions
type ZodErrorMap ¶
type ZodErrorMap func(ZodRawIssue) string
ZodErrorMap represents a function that maps raw issues to error messages Allows customization of error messages based on validation context
type ZodIssue ¶
type ZodIssue struct {
ZodIssueBase
Expected ZodTypeCode `json:"expected,omitempty"` // Expected type or value
Received ZodTypeCode `json:"received,omitempty"` // Actual type or value
Minimum any `json:"minimum,omitempty"` // Minimum value for range checks
Maximum any `json:"maximum,omitempty"` // Maximum value for range checks
Inclusive bool `json:"inclusive,omitempty"` // Whether range bounds are inclusive
Keys []string `json:"keys,omitempty"` // Keys for unrecognized_keys errors
Options []any `json:"options,omitempty"` // Valid options for literal errors
Errors [][]ZodIssue `json:"errors,omitempty"` // Nested errors for union types
Issues []ZodIssue `json:"issues,omitempty"` // Sub-issues for complex validations
Format string `json:"format,omitempty"` // Expected format for format validation
Divisor any `json:"divisor,omitempty"` // Divisor for multiple_of validation
Pattern string `json:"pattern,omitempty"` // Regex pattern for string validation
Includes string `json:"includes,omitempty"` // Substring for includes validation
Prefix string `json:"prefix,omitempty"` // Prefix for starts_with validation
Suffix string `json:"suffix,omitempty"` // Suffix for ends_with validation
Values []any `json:"values,omitempty"` // Valid values for enum validation
Algorithm string `json:"algorithm,omitempty"` // Algorithm for JWT validation
Origin string `json:"origin,omitempty"` // Origin type for size validation
Key any `json:"key,omitempty"` // Key for invalid element errors
Params map[string]any `json:"params,omitempty"` // Custom parameters for validation
}
ZodIssue represents a finalized validation issue This is the final form of validation issues after processing
func (ZodIssue) GetDivisor ¶
GetDivisor returns the divisor for not_multiple_of issues
func (ZodIssue) GetExpected ¶
func (i ZodIssue) GetExpected() (ZodTypeCode, bool)
GetExpected returns the expected type for invalid_type issues
func (*ZodIssue) GetMaximum ¶
GetMaximum returns the maximum value if present
func (*ZodIssue) GetMinimum ¶
GetMinimum returns the minimum value if present
func (ZodIssue) GetReceived ¶
func (i ZodIssue) GetReceived() (ZodTypeCode, bool)
GetReceived returns the received type for invalid_type issues
type ZodIssueBase ¶
type ZodIssueBase struct {
Code IssueCode `json:"code,omitempty"` // Issue type identifier
Input any `json:"input,omitempty"` // The input that caused the issue
Path []any `json:"path"` // Path to the problematic field
Message string `json:"message"` // Human-readable error message
}
ZodIssueBase represents the base structure for all validation issues Contains common fields that all validation issues share
type ZodIssueInvalidType ¶
type ZodIssueInvalidType struct {
ZodIssueBase
Expected ZodTypeCode `json:"expected"` // Expected type name
Received ZodTypeCode `json:"received"` // Actual type name
}
ZodIssueInvalidType represents invalid type error Used when the input type doesn't match the expected type
type ZodIssueInvalidValue ¶
type ZodIssueInvalidValue struct {
ZodIssueBase
Options []any `json:"options"` // List of valid options
}
ZodIssueInvalidValue represents invalid value error Used when the input value is not in the allowed set
type ZodPipe ¶ added in v0.3.0
type ZodPipe[In, Out any] struct { // contains filtered or unexported fields }
ZodPipe represents a pipeline using the WrapFn pattern. Instead of holding a target schema object, it uses a target function created by wrapfn.
Design Philosophy:
- Direct function composition eliminates adapter overhead
- Each type implements its own wrapfn logic for type conversion
- Cleaner architecture with better performance
Generic Parameters:
- In: The input type for the source schema
- Out: The output type from the target function
Key Innovation:
- targetFn: A function that handles type conversion and target validation
- Created by each type's Pipe method using wrapfn pattern
- No need for adapter objects or converters
func NewZodPipe ¶ added in v0.3.0
func NewZodPipe[In, Out any](source ZodType[In], target ZodType[any], targetFn func(In, *ParseContext) (Out, error)) *ZodPipe[In, Out]
NewZodPipe creates a new pipeline schema with explicit target schema information.
func (*ZodPipe[In, Out]) GetInner ¶ added in v0.3.1
GetInner returns the input (source) schema, used by JSON-Schema converter for IO:"input" mode.
func (*ZodPipe[In, Out]) GetInternals ¶ added in v0.3.0
func (z *ZodPipe[In, Out]) GetInternals() *ZodTypeInternals
GetInternals returns the internal state of this pipeline schema.
func (*ZodPipe[In, Out]) GetOutput ¶ added in v0.3.1
GetOutput returns the output (target) schema, used by JSON-Schema converter for IO:"output" mode.
func (*ZodPipe[In, Out]) IsNilable ¶ added in v0.3.0
IsNilable returns true if this schema accepts nil values
func (*ZodPipe[In, Out]) IsOptional ¶ added in v0.3.0
IsOptional returns true if this schema accepts undefined/missing values
func (*ZodPipe[In, Out]) MustParse ¶ added in v0.3.0
func (z *ZodPipe[In, Out]) MustParse(input any, ctx ...*ParseContext) Out
MustParse validates through the pipeline, panicking on error.
func (*ZodPipe[In, Out]) Parse ¶ added in v0.3.0
func (z *ZodPipe[In, Out]) Parse(input any, ctx ...*ParseContext) (Out, error)
Parse validates input through the wrapfn pipeline: source schema -> target function.
func (*ZodPipe[In, Middle]) Pipe ¶ added in v0.3.0
Pipe allows chaining ZodPipe into another ZodPipe.
func (*ZodPipe[In, Middle]) Transform ¶ added in v0.3.0
func (z *ZodPipe[In, Middle]) Transform(fn func(Middle, *RefinementContext) (any, error)) *ZodTransform[Middle, any]
Transform allows chaining transformations on ZodPipe.
type ZodRawIssue ¶
type ZodRawIssue struct {
Code IssueCode `json:"code"` // Issue type code
Input any `json:"input,omitempty"` // Input value that failed
Path []any `json:"path,omitempty"` // Field path in nested structures
Message string `json:"message,omitempty"` // Error message
Properties map[string]any `json:"properties,omitempty"` // Additional issue properties
Continue bool `json:"-"` // Whether to continue validation
Inst any `json:"-"` // Instance that generated the issue
}
ZodRawIssue represents a raw issue before finalization Used internally during validation before converting to final ZodIssue
func (ZodRawIssue) GetDivisor ¶
func (r ZodRawIssue) GetDivisor() any
GetDivisor returns the divisor value from properties map
func (ZodRawIssue) GetExpected ¶
func (r ZodRawIssue) GetExpected() ZodTypeCode
GetExpected returns the expected value from properties map
func (ZodRawIssue) GetFormat ¶
func (r ZodRawIssue) GetFormat() string
GetFormat returns the format value from properties map
func (ZodRawIssue) GetIncludes ¶
func (r ZodRawIssue) GetIncludes() string
GetIncludes returns the includes value from properties map
func (ZodRawIssue) GetInclusive ¶
func (r ZodRawIssue) GetInclusive() bool
GetInclusive returns the inclusive value from properties map
func (ZodRawIssue) GetKeys ¶
func (r ZodRawIssue) GetKeys() []string
GetKeys returns the keys value from properties map
func (ZodRawIssue) GetMaximum ¶
func (r ZodRawIssue) GetMaximum() any
GetMaximum returns the maximum value from properties map
func (ZodRawIssue) GetMinimum ¶
func (r ZodRawIssue) GetMinimum() any
GetMinimum returns the minimum value from properties map
func (ZodRawIssue) GetOrigin ¶
func (r ZodRawIssue) GetOrigin() string
GetOrigin returns the origin value from properties map
func (ZodRawIssue) GetPattern ¶
func (r ZodRawIssue) GetPattern() string
GetPattern returns the pattern value from properties map
func (ZodRawIssue) GetPrefix ¶
func (r ZodRawIssue) GetPrefix() string
GetPrefix returns the prefix value from properties map
func (ZodRawIssue) GetReceived ¶
func (r ZodRawIssue) GetReceived() ZodTypeCode
GetReceived returns the received value from properties map
func (ZodRawIssue) GetSuffix ¶
func (r ZodRawIssue) GetSuffix() string
GetSuffix returns the suffix value from properties map
func (ZodRawIssue) GetValues ¶
func (r ZodRawIssue) GetValues() []any
GetValues returns the values from properties map
type ZodRefineFn ¶ added in v0.3.0
ZodRefineFn defines the signature for a simple, type-safe refinement. It's a helper for checks that only need to return a boolean result.
type ZodSchema ¶ added in v0.3.0
type ZodSchema interface {
// ParseAny validates input and returns an untyped `any` result. This is
// crucial for dynamic structures like maps or objects.
ParseAny(input any, ctx ...*ParseContext) (any, error)
// GetInternals provides access to the internal state of this schema.
GetInternals() *ZodTypeInternals
}
ZodSchema is a non-generic version of the schema interface, used for dynamic validation at runtime when the specific type `T` is not known.
func ConvertToZodSchema ¶ added in v0.3.0
ConvertToZodSchema converts a value to the ZodSchema interface, returning an error if the type does not implement the interface.
type ZodTransform ¶ added in v0.3.0
type ZodTransform[In, Out any] struct { // contains filtered or unexported fields }
ZodTransform represents a schema that applies a function to a validated value. It is returned by the `.transform()` method on any schema.
Generic Parameters:
- In: The input type that the source schema validates.
- Out: The output type that the transformation function produces.
func NewZodTransform ¶ added in v0.3.0
func NewZodTransform[In, Out any](source ZodType[In], wrapperFn func(In, *RefinementContext) (Out, error)) *ZodTransform[In, Out]
NewZodTransform creates a new transformation schema. This is used by each type's Transform method with their own wrapfn logic.
Parameters:
- source: The source schema
- wrapperFn: The wrapper function created by the type's Transform method
Returns:
- *ZodTransform[In, Out]: A new transformation schema
func (*ZodTransform[In, Out]) GetInner ¶ added in v0.3.1
func (z *ZodTransform[In, Out]) GetInner() ZodSchema
GetInner returns the input schema for the transformation.
func (*ZodTransform[In, Out]) GetInternals ¶ added in v0.3.0
func (z *ZodTransform[In, Out]) GetInternals() *ZodTypeInternals
GetInternals returns the internal state of this transformation schema.
func (*ZodTransform[In, Out]) IsNilable ¶ added in v0.3.0
func (z *ZodTransform[In, Out]) IsNilable() bool
IsNilable returns true if this schema accepts nil values
func (*ZodTransform[In, Out]) IsOptional ¶ added in v0.3.0
func (z *ZodTransform[In, Out]) IsOptional() bool
IsOptional returns true if this schema accepts undefined/missing values
func (*ZodTransform[In, Out]) MustParse ¶ added in v0.3.0
func (z *ZodTransform[In, Out]) MustParse(input any, ctx ...*ParseContext) Out
MustParse validates and transforms input, panicking on error.
func (*ZodTransform[In, Out]) Parse ¶ added in v0.3.0
func (z *ZodTransform[In, Out]) Parse(input any, ctx ...*ParseContext) (Out, error)
Parse validates input with the source schema, then applies the transformation. Follows Zod v4 semantics: Default/DefaultFunc values skip transformation completely.
func (*ZodTransform[In, Out]) ParseAny ¶ added in v0.3.1
func (z *ZodTransform[In, Out]) ParseAny(input any, ctx ...*ParseContext) (any, error)
ParseAny validates and transforms input, returning an untyped result.
func (*ZodTransform[In, Middle]) Pipe ¶ added in v0.3.0
func (z *ZodTransform[In, Middle]) Pipe(target ZodType[any]) *ZodPipe[Middle, any]
Pipe allows chaining ZodTransform into ZodPipe.
func (*ZodTransform[In, Middle]) Transform ¶ added in v0.3.0
func (z *ZodTransform[In, Middle]) Transform(fn func(Middle, *RefinementContext) (any, error)) *ZodTransform[Middle, any]
Transform allows chaining transformations on ZodTransform.
type ZodType ¶
type ZodType[T any] interface { // Parse validates the input against this schema and returns the typed result. // This is the core validation method. Parse(input any, ctx ...*ParseContext) (T, error) // MustParse is a convenience method that validates input and panics on error. // It simplifies code where validation is expected to succeed. MustParse(input any, ctx ...*ParseContext) T // GetInternals provides access to the internal state of this schema, // allowing for advanced composition and framework integration. GetInternals() *ZodTypeInternals // IsOptional returns true if this schema accepts undefined/missing values. // This is a convenience method equivalent to GetInternals().IsOptional(). IsOptional() bool // IsNilable returns true if this schema accepts nil values. // This is a convenience method equivalent to GetInternals().IsNilable(). IsNilable() bool }
ZodType is the universal interface for all validation schemas. It is the cornerstone of `gozod`, providing a consistent API for any data type.
Generic Parameter:
- T: The output type that this schema validates and returns.
type ZodTypeCode ¶ added in v0.2.2
type ZodTypeCode string
ZodTypeCode represents a type-safe wrapper for schema type identifiers This provides compile-time type safety and better IDE support
const ( // Primitive types ZodTypeString ZodTypeCode = "string" // String validation schema ZodTypeNumber ZodTypeCode = "number" // Generic number validation ZodTypeNaN ZodTypeCode = "nan" // NaN value validation ZodTypeInteger ZodTypeCode = "integer" // Integer validation ZodTypeBigInt ZodTypeCode = "bigint" // Big integer validation ZodTypeBool ZodTypeCode = "bool" // Boolean validation ZodTypeDate ZodTypeCode = "date" // Date validation ZodTypeNil ZodTypeCode = "nil" // Nil/null validation // Special types ZodTypeAny ZodTypeCode = "any" // Accept any value ZodTypeUnknown ZodTypeCode = "unknown" // Unknown type (safer any) ZodTypeNever ZodTypeCode = "never" // Never accepts value // Collection types ZodTypeArray ZodTypeCode = "array" // Fixed-length array ZodTypeSlice ZodTypeCode = "slice" // Dynamic array/slice ZodTypeTuple ZodTypeCode = "tuple" // Fixed-length tuple with heterogeneous types ZodTypeObject ZodTypeCode = "object" // Object with known shape ZodTypeStruct ZodTypeCode = "struct" // Go struct validation ZodTypeRecord ZodTypeCode = "record" // Key-value record ZodTypeMap ZodTypeCode = "map" // Go map validation ZodTypeSet ZodTypeCode = "set" // Set validation (map[T]struct{}) // Composite types ZodTypeUnion ZodTypeCode = "union" // Union of multiple types (anyOf) ZodTypeXor ZodTypeCode = "xor" // Exclusive union (oneOf) - exactly one must match ZodTypeDiscriminated ZodTypeCode = "discriminated_union" // Discriminated union ZodTypeIntersection ZodTypeCode = "intersection" // Intersection of types // Special string types ZodTypeStringBool ZodTypeCode = "stringbool" // String representation of boolean // Function and lazy types ZodTypeFunction ZodTypeCode = "function" // Function validation ZodTypeLazy ZodTypeCode = "lazy" // Lazy evaluation schema // Value types ZodTypeLiteral ZodTypeCode = "literal" // Literal value validation ZodTypeEnum ZodTypeCode = "enum" // Enumeration validation // Modifier types ZodTypeOptional ZodTypeCode = "optional" // Optional field modifier ZodTypeNilable ZodTypeCode = "nilable" // Nilable field modifier ZodTypeDefault ZodTypeCode = "default" // Default value wrapper ZodTypePrefault ZodTypeCode = "prefault" // Fallback value wrapper // Processing types ZodTypePipeline ZodTypeCode = "pipeline" // Processing pipeline ZodTypeTransform ZodTypeCode = "transform" // Value transformation ZodTypePipe ZodTypeCode = "pipe" // Schema piping ZodTypeCustom ZodTypeCode = "custom" // Custom validation ZodTypeCheck ZodTypeCode = "check" // Validation check ZodTypeRefine ZodTypeCode = "refine" // Refinement validation // Network and format types ZodTypeIPv4 ZodTypeCode = "ipv4" // IPv4 address validation ZodTypeIPv6 ZodTypeCode = "ipv6" // IPv6 address validation ZodTypeCIDRv4 ZodTypeCode = "cidrv4" // IPv4 CIDR validation ZodTypeCIDRv6 ZodTypeCode = "cidrv6" // IPv6 CIDR validation ZodTypeEmail ZodTypeCode = "email" // Email address validation ZodTypeURL ZodTypeCode = "url" // URL validation ZodTypeHostname ZodTypeCode = "hostname" // DNS hostname validation ZodTypeMAC ZodTypeCode = "mac" // MAC address validation ZodTypeE164 ZodTypeCode = "e164" // E.164 phone number validation // Time types ZodTypeTime ZodTypeCode = "time" // Go time.Time validation // ISO 8601 format validation types ZodTypeIso ZodTypeCode = "iso" // ISO 8601 format validation ZodTypeISODateTime ZodTypeCode = "iso_datetime" // ISO 8601 datetime validation ZodTypeISODate ZodTypeCode = "iso_date" // ISO 8601 date validation ZodTypeISOTime ZodTypeCode = "iso_time" // ISO 8601 time validation ZodTypeISODuration ZodTypeCode = "iso_duration" // ISO 8601 duration validation // File and binary types ZodTypeFile ZodTypeCode = "file" // File validation // Numeric subtypes ZodTypeFloat32 ZodTypeCode = "float32" // 32-bit float ZodTypeFloat64 ZodTypeCode = "float64" // 64-bit float ZodTypeFloat ZodTypeCode = "float" // Flexible float type (accepts float32, float64) ZodTypeInt ZodTypeCode = "int" // Flexible integer type (accepts all integer types) ZodTypeInt8 ZodTypeCode = "int8" // 8-bit signed integer ZodTypeInt16 ZodTypeCode = "int16" // 16-bit signed integer ZodTypeInt32 ZodTypeCode = "int32" // 32-bit signed integer ZodTypeInt64 ZodTypeCode = "int64" // 64-bit signed integer ZodTypeUint ZodTypeCode = "uint" // Platform-dependent unsigned integer ZodTypeUint8 ZodTypeCode = "uint8" // 8-bit unsigned integer ZodTypeUint16 ZodTypeCode = "uint16" // 16-bit unsigned integer ZodTypeUint32 ZodTypeCode = "uint32" // 32-bit unsigned integer ZodTypeUint64 ZodTypeCode = "uint64" // 64-bit unsigned integer ZodTypeUintptr ZodTypeCode = "uintptr" // Pointer-sized unsigned integer ZodTypeComplex64 ZodTypeCode = "complex64" // 64-bit complex number ZodTypeComplex128 ZodTypeCode = "complex128" // 128-bit complex number ZodTypeNonOptional ZodTypeCode = "nonoptional" // Special type identifier for non-optional fields )
ZodType constants define the type identifiers for all schema types These are used internally to identify and categorize schema types
type ZodTypeDef ¶
type ZodTypeDef struct {
Type ZodTypeCode // Type name using type-safe constants
Coerce bool // Enable coercion
Required bool // Field is required
Error *ZodErrorMap // Custom error handler
Checks []ZodCheck // Validation checks
}
ZodTypeDef represents the base configuration for creating any schema type. It's a blueprint used by type constructors.
type ZodTypeInternals ¶
type ZodTypeInternals struct {
Type ZodTypeCode // Type identifier using type-safe constants
Checks []ZodCheck // List of validation checks to apply
Parse func(payload *ParsePayload, ctx *ParseContext) *ParsePayload // The core parsing function for the type
// Core validation flags
Coerce bool // Whether to enable type coercion
Optional bool // Whether the field is optional
Nilable bool // Whether nil values are allowed
NonOptional bool // True if .NonOptional() was applied, for error reporting
ExactOptional bool // True if .ExactOptional() was applied - accepts absent keys but rejects explicit nil
// Default/Prefault values
DefaultValue any
DefaultFunc func() any
PrefaultValue any
PrefaultFunc func() any
// Modifier priority tracking (higher number = applied later = higher priority)
OptionalPriority int // Priority when Optional/Nilable was applied
PrefaultPriority int // Priority when Prefault was applied
DefaultPriority int // Priority when Default was applied
// Transform function
Transform func(any, *RefinementContext) (any, error)
// Optionality configuration
OptIn string // Optionality mode input
OptOut string // Optionality mode output
// Constructor and configuration
Constructor func(def *ZodTypeDef) ZodType[any] // Factory function
Values map[any]struct{} // Valid values for literal types
Pattern *regexp.Regexp // Regex pattern for string validation
Error *ZodErrorMap // Custom error mapping
Bag map[string]any // Additional configuration storage
}
ZodTypeInternals holds the complete configuration and state for any schema. It acts as the backbone, storing everything from validation checks to default values and custom error maps.
func (*ZodTypeInternals) AddCheck ¶ added in v0.3.0
func (z *ZodTypeInternals) AddCheck(check ZodCheck)
AddCheck adds a validation check to the internals.
func (*ZodTypeInternals) Clone ¶ added in v0.3.0
func (z *ZodTypeInternals) Clone() *ZodTypeInternals
Clone creates a deep copy of the internals for immutable modifications.
func (*ZodTypeInternals) IsCoerce ¶ added in v0.2.2
func (z *ZodTypeInternals) IsCoerce() bool
IsCoerce returns true if type coercion is enabled.
func (*ZodTypeInternals) IsExactOptional ¶ added in v0.5.4
func (z *ZodTypeInternals) IsExactOptional() bool
IsExactOptional returns true if exact optional mode is enabled. ExactOptional accepts absent keys but rejects explicit nil values.
func (*ZodTypeInternals) IsNilable ¶ added in v0.2.2
func (z *ZodTypeInternals) IsNilable() bool
IsNilable returns true if nil values are allowed.
func (*ZodTypeInternals) IsNonOptional ¶ added in v0.3.0
func (z *ZodTypeInternals) IsNonOptional() bool
IsNonOptional returns true if the field is non-optional.
func (*ZodTypeInternals) IsOptional ¶ added in v0.2.2
func (z *ZodTypeInternals) IsOptional() bool
IsOptional returns true if the field is optional.
func (*ZodTypeInternals) SetCoerce ¶ added in v0.2.2
func (z *ZodTypeInternals) SetCoerce(value bool)
SetCoerce enables type coercion for this field.
func (*ZodTypeInternals) SetDefaultFunc ¶ added in v0.3.0
func (z *ZodTypeInternals) SetDefaultFunc(fn func() any)
SetDefaultFunc sets a default value function.
func (*ZodTypeInternals) SetDefaultValue ¶ added in v0.3.0
func (z *ZodTypeInternals) SetDefaultValue(value any)
SetDefaultValue sets a default value.
func (*ZodTypeInternals) SetExactOptional ¶ added in v0.5.4
func (z *ZodTypeInternals) SetExactOptional(value bool)
SetExactOptional enables exact optional mode. ExactOptional accepts absent keys but rejects explicit nil values.
Note: This also sets Optional=true because ExactOptional implies Optional semantics for absent key handling. The difference between ExactOptional and Optional is only in nil rejection - ExactOptional rejects explicit nil values while Optional accepts them.
func (*ZodTypeInternals) SetNilable ¶ added in v0.2.2
func (z *ZodTypeInternals) SetNilable(value bool)
SetNilable allows nil values for this field.
func (*ZodTypeInternals) SetNonOptional ¶ added in v0.3.0
func (z *ZodTypeInternals) SetNonOptional(value bool)
SetNonOptional marks the field as nonoptional (disallow nil with custom expected tag).
func (*ZodTypeInternals) SetOptional ¶ added in v0.2.2
func (z *ZodTypeInternals) SetOptional(value bool)
SetOptional marks the field as optional.
func (*ZodTypeInternals) SetPrefaultFunc ¶ added in v0.3.0
func (z *ZodTypeInternals) SetPrefaultFunc(fn func() any)
SetPrefaultFunc sets a prefault value function.
func (*ZodTypeInternals) SetPrefaultValue ¶ added in v0.3.0
func (z *ZodTypeInternals) SetPrefaultValue(value any)
SetPrefaultValue sets a prefault value.
func (*ZodTypeInternals) SetTransform ¶ added in v0.3.0
func (z *ZodTypeInternals) SetTransform(fn func(any, *RefinementContext) (any, error))
SetTransform sets a transform function.
type ZodWhenFn ¶
type ZodWhenFn func(payload *ParsePayload) bool
ZodWhenFn defines the signature for a conditional predicate function. It is used to determine if a check should be executed based on the payload.