Documentation
¶
Overview ¶
Package core provides the foundation contracts for the gozod validation library, including interfaces, types, and constants used throughout the system.
Package core provides the foundational types, interfaces, and constants shared by all schema implementations in the gozod validation library.
Index ¶
- Variables
- func ApplyGlobalMeta(source, target ZodSchema, update GlobalMeta)
- func ApplyRefinements[S Refineable[S]](schema S, rules []func(any) bool) S
- func AttachCheck(schema ZodSchema, check ZodCheck)
- func AttachChecks(schema ZodSchema)
- func CopyGlobalMeta(from, to ZodSchema)
- func DescribeSchema[S Describable[S]](schema S, desc string) S
- func MetaSchema[S Describable[S]](schema S, meta GlobalMeta) S
- type CheckParams
- type Cloneable
- type CustomParams
- type Describable
- 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) Context() *ParseContext
- func (p *ParsePayload) HasIssues() bool
- func (p *ParsePayload) IssueCount() int
- func (p *ParsePayload) Issues() []ZodRawIssue
- func (p *ParsePayload) Path() []any
- func (p *ParsePayload) PushPath(element any)
- func (p *ParsePayload) SetContext(ctx *ParseContext)
- func (p *ParsePayload) SetIssues(issues []ZodRawIssue)
- func (p *ParsePayload) SetValue(v any)
- func (p *ParsePayload) Value() any
- func (p *ParsePayload) WithCleanIssues() *ParsePayload
- type ParsedType
- type Refineable
- type RefinementContext
- type Registry
- type SchemaParams
- type StrictZodType
- type StructSchema
- type Unwrapper
- type ZodCheck
- type ZodCheckDef
- type ZodCheckFn
- type ZodCheckInternals
- type ZodConfig
- type ZodCustomParams
- type ZodErrorMap
- type ZodIssue
- func (z ZodIssue) DivisorValue() (any, bool)
- func (z ZodIssue) Error() string
- func (z ZodIssue) ExpectedType() (ZodTypeCode, bool)
- func (z ZodIssue) FormatName() (string, bool)
- func (z *ZodIssue) MaxValue() (any, bool)
- func (z *ZodIssue) MinValue() (any, bool)
- func (z ZodIssue) ReceivedType() (ZodTypeCode, bool)
- func (z ZodIssue) String() string
- type ZodIssueBase
- type ZodIssueInvalidType
- type ZodIssueInvalidValue
- type ZodModifier
- type ZodModifierKind
- type ZodPipe
- func (p *ZodPipe[In, Out]) Inner() ZodSchema
- func (p *ZodPipe[In, Out]) Internals() *ZodTypeInternals
- func (p *ZodPipe[In, Out]) IsNilable() bool
- func (p *ZodPipe[In, Out]) IsOptional() bool
- func (p *ZodPipe[In, Out]) MustParse(input any, ctx ...*ParseContext) Out
- func (p *ZodPipe[In, Out]) Output() ZodSchema
- func (p *ZodPipe[In, Out]) Parse(input any, ctx ...*ParseContext) (out Out, _ error)
- func (p *ZodPipe[In, Out]) ParseAny(input any, ctx ...*ParseContext) (any, error)
- func (p *ZodPipe[In, Middle]) Pipe(target ZodType[any]) *ZodPipe[Middle, any]
- func (p *ZodPipe[In, Middle]) Transform(fn func(Middle, *RefinementContext) (any, error)) *ZodTransform[Middle, any]
- type ZodRawIssue
- func (r ZodRawIssue) Divisor() any
- func (r ZodRawIssue) Expected() ZodTypeCode
- func (r ZodRawIssue) Format() string
- func (r ZodRawIssue) Includes() string
- func (r ZodRawIssue) Inclusive() bool
- func (r ZodRawIssue) Keys() []string
- func (r ZodRawIssue) Maximum() any
- func (r ZodRawIssue) Minimum() any
- func (r ZodRawIssue) Origin() string
- func (r ZodRawIssue) Pattern() string
- func (r ZodRawIssue) Prefix() string
- func (r ZodRawIssue) Received() ZodTypeCode
- func (r ZodRawIssue) Suffix() string
- func (r ZodRawIssue) Values() []any
- type ZodRefineFn
- type ZodSchema
- type ZodTransform
- func (t *ZodTransform[In, Out]) Inner() ZodSchema
- func (t *ZodTransform[In, Out]) Internals() *ZodTypeInternals
- func (t *ZodTransform[In, Out]) IsNilable() bool
- func (t *ZodTransform[In, Out]) IsOptional() bool
- func (t *ZodTransform[In, Out]) MustParse(input any, ctx ...*ParseContext) Out
- func (t *ZodTransform[In, Out]) Parse(input any, ctx ...*ParseContext) (out Out, _ error)
- func (t *ZodTransform[In, Out]) ParseAny(input any, ctx ...*ParseContext) (any, error)
- func (t *ZodTransform[In, Middle]) Pipe(target ZodType[any]) *ZodPipe[Middle, any]
- func (t *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) NilInputUsesDefault() 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")
ErrInvalidTransformType is returned when a type assertion fails during transformation.
var ErrSchemaNotZodSchema = errors.New("schema does not implement ZodSchema interface")
ErrSchemaNotZodSchema is a sentinel error returned when a value does not implement the ZodSchema interface.
var GlobalRegistry = NewRegistry[GlobalMeta]()
GlobalRegistry is the default, framework-provided global registry for convenient, shared metadata collection.
Functions ¶
func ApplyGlobalMeta ¶ added in v0.11.5
func ApplyGlobalMeta(source, target ZodSchema, update GlobalMeta)
ApplyGlobalMeta merges update from source metadata and stores it on target.
func ApplyRefinements ¶ added in v0.6.6
func ApplyRefinements[S Refineable[S]](schema S, rules []func(any) bool) S
ApplyRefinements applies multiple validation rules to any Refineable schema.
func AttachCheck ¶ added in v0.11.5
AttachCheck runs a check's construction-time attachment hooks on schema.
func AttachChecks ¶ added in v0.11.5
func AttachChecks(schema ZodSchema)
AttachChecks runs construction-time attachment hooks for all schema checks.
func CopyGlobalMeta ¶ added in v0.10.0
func CopyGlobalMeta(from, to ZodSchema)
CopyGlobalMeta copies metadata from one schema instance to another.
func DescribeSchema ¶ added in v0.6.6
func DescribeSchema[S Describable[S]](schema S, desc string) S
DescribeSchema applies a description to any Describable schema, returning the same concrete type.
func MetaSchema ¶ added in v0.6.6
func MetaSchema[S Describable[S]](schema S, meta GlobalMeta) S
MetaSchema applies metadata to any Describable schema, returning the same concrete type.
Types ¶
type CheckParams ¶ added in v0.3.0
type CheckParams struct {
Error string
}
CheckParams defines parameters for attaching a validation check.
type Cloneable ¶
type Cloneable interface {
// CloneFrom copies configuration from a source schema instance.
CloneFrom(source any)
}
Cloneable is an optional interface for schemas that support deep-copying. This is essential for copy-on-write modifiers like .Optional() or .Transform().
type CustomParams ¶ added in v0.3.1
type CustomParams struct {
Error any `json:"error,omitempty"`
Abort bool `json:"abort,omitempty"`
Path []any `json:"path,omitempty"`
When ZodWhenFn `json:"-"`
Params map[string]any `json:"params,omitempty"`
}
CustomParams represents parameters for custom validation checks.
type Describable ¶ added in v0.6.6
type Describable[S Describable[S]] interface { Describe(string) S Meta(GlobalMeta) S Internals() *ZodTypeInternals }
Describable defines the fluent metadata contract.
This is intentionally separate from ZodSchema/ZodType because metadata chaining is not required by dynamic runtime code paths. The self-referential constraint ensures Describe and Meta return the concrete schema type.
Go 1.26 self-referential generic constraint.
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.
func MergeGlobalMeta ¶ added in v0.11.5
func MergeGlobalMeta(base, update GlobalMeta) GlobalMeta
MergeGlobalMeta overlays update on base, keeping base fields when update leaves them empty.
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" InvalidValue IssueCode = "invalid_value" InvalidFormat IssueCode = "invalid_format" InvalidUnion IssueCode = "invalid_union" InvalidKey IssueCode = "invalid_key" InvalidElement IssueCode = "invalid_element" // Range validation issues TooBig IssueCode = "too_big" TooSmall IssueCode = "too_small" NotMultipleOf IssueCode = "not_multiple_of" // Structure validation issues UnrecognizedKeys IssueCode = "unrecognized_keys" // Custom validation issues Custom IssueCode = "custom" // Schema validation issues InvalidSchema IssueCode = "invalid_schema" // Discriminator validation issues InvalidDiscriminator IssueCode = "invalid_discriminator" // Intersection validation issues IncompatibleTypes IssueCode = "incompatible_types" // New validation issues MissingRequired IssueCode = "missing_required" TypeConversion IssueCode = "type_conversion" NilPointer IssueCode = "nil_pointer" )
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 ZodErrorMap // Custom error message generator
ReportInput bool // Include original input in issues
IsPrefaultContext bool // Whether parsing a prefault value
}
ParseContext contains the configuration and state for a validation run.
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.
type ParsePayload ¶
type ParsePayload struct {
// contains filtered or unexported fields
}
ParsePayload contains the value and validation issues during parsing.
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 appends a validation issue, prepending the current path.
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.
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) Context ¶ added in v0.10.0
func (p *ParsePayload) Context() *ParseContext
Context returns the parse context driving this payload, if any.
func (*ParsePayload) HasIssues ¶
func (p *ParsePayload) HasIssues() bool
HasIssues reports whether the payload has any validation issues.
func (*ParsePayload) IssueCount ¶ added in v0.6.0
func (p *ParsePayload) IssueCount() int
IssueCount returns the number of validation issues.
func (*ParsePayload) Issues ¶
func (p *ParsePayload) Issues() []ZodRawIssue
Issues returns a copy of the current validation issues.
func (*ParsePayload) Path ¶
func (p *ParsePayload) Path() []any
Path returns a copy of the current validation path.
func (*ParsePayload) PushPath ¶
func (p *ParsePayload) PushPath(element any)
PushPath adds a path element to the current validation path.
func (*ParsePayload) SetContext ¶ added in v0.10.0
func (p *ParsePayload) SetContext(ctx *ParseContext)
SetContext attaches the parse context driving this payload.
func (*ParsePayload) SetIssues ¶ added in v0.2.4
func (p *ParsePayload) SetIssues(issues []ZodRawIssue)
SetIssues replaces the issues slice.
func (*ParsePayload) SetValue ¶ added in v0.2.4
func (p *ParsePayload) SetValue(v any)
SetValue assigns a new value to the payload.
func (*ParsePayload) Value ¶
func (p *ParsePayload) Value() any
Value returns the current value being validated.
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" ParsedTypeNumber ParsedType = "number" ParsedTypeBigint ParsedType = "bigint" ParsedTypeBool ParsedType = "bool" ParsedTypeFloat ParsedType = "float" ParsedTypeObject ParsedType = "object" ParsedTypeFunction ParsedType = "function" ParsedTypeFile ParsedType = "file" ParsedTypeDate ParsedType = "date" ParsedTypeArray ParsedType = "array" ParsedTypeSlice ParsedType = "slice" ParsedTypeTuple ParsedType = "tuple" ParsedTypeMap ParsedType = "map" ParsedTypeSet ParsedType = "set" ParsedTypeNaN ParsedType = "nan" ParsedTypeNil ParsedType = "nil" ParsedTypeComplex ParsedType = "complex" ParsedTypeStruct ParsedType = "struct" ParsedTypeEnum ParsedType = "enum" ParsedTypeUnknown ParsedType = "unknown" )
type Refineable ¶ added in v0.6.6
type Refineable[S Refineable[S]] interface { RefineAny(func(any) bool, ...any) S Internals() *ZodTypeInternals }
Refineable defines the fluent refinement contract.
This stays separate from the minimal runtime interfaces so callers can write helpers against refinement-capable schemas without implying every runtime dependency must also know about fluent validation APIs.
Go 1.26 self-referential generic constraint.
type RefinementContext ¶
type RefinementContext struct {
*ParseContext
Value any // The value being refined/transformed
AddIssue func(issue ZodIssue) // Function to add validation issues
// contains filtered or unexported fields
}
RefinementContext provides context for refinement and transformation operations.
func NewRefinementContext ¶ added in v0.10.0
func NewRefinementContext(ctx *ParseContext, value any) *RefinementContext
NewRefinementContext creates a refinement context for the given value and parse context.
func (*RefinementContext) Err ¶ added in v0.10.0
func (ctx *RefinementContext) Err() error
Err returns a combined error for the issues added via AddIssue.
func (*RefinementContext) Issues ¶ added in v0.10.0
func (ctx *RefinementContext) Issues() []ZodIssue
Issues returns a copy of the issues added via AddIssue.
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.
func (*Registry[M]) Range ¶ added in v0.3.1
Range iterates over the schemas and metadata in the registry. If the callback function returns false, iteration stops.
Important: The callback is executed while holding a read lock. Avoid performing expensive operations or calling back into the registry within the callback, as this may cause deadlocks or performance issues.
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 StrictZodType ¶ added in v0.10.0
type StrictZodType[In, Out any] interface { ZodType[Out] // StrictParse validates a compile-time constrained input. StrictParse(input In, ctx ...*ParseContext) (Out, error) // MustStrictParse validates constrained input and panics on error. MustStrictParse(input In, ctx ...*ParseContext) Out }
StrictZodType extends ZodType with compile-time constrained parsing.
Input and output are separate because many schemas accept a base type T while returning a constraint type R such as *T. This interface models the "strict side" of the API surface only; fluent metadata and refinement contracts remain separate.
type StructSchema ¶
StructSchema defines the shape of a struct for validation. It maps field names to their corresponding validation schemas.
type Unwrapper ¶ added in v0.8.0
type Unwrapper interface {
// Unwrap returns the underlying value and whether it is present.
// If ok is false, the value should not be validated.
Unwrap() (value any, ok bool)
}
Unwrapper allows wrapper types to expose their underlying value for validation. This enables validation of types like Optional[T], sql.NullString, etc.
Example:
type Optional[T any] struct {
Value T
set bool
}
func (o Optional[T]) Unwrap() (any, bool) {
return o.Value, o.set
}
type ZodCheck ¶
type ZodCheck interface {
Zod() *ZodCheckInternals
}
ZodCheck represents the interface for any validation constraint.
type ZodCheckDef ¶
type ZodCheckDef struct {
Check string
Params map[string]any
Error *ZodErrorMap
Abort bool
}
ZodCheckDef defines the static configuration for a validation check.
func NewZodCheckDef ¶ added in v0.11.5
func NewZodCheckDef(check string, params map[string]any) *ZodCheckDef
NewZodCheckDef creates a check definition with cloned semantic parameters.
type ZodCheckFn ¶
type ZodCheckFn func(payload *ParsePayload)
ZodCheckFn defines the signature for a validation function.
type ZodCheckInternals ¶
type ZodCheckInternals struct {
Def *ZodCheckDef
Issue *ZodIssueBase
Check ZodCheckFn
OnAttach []func(schema any)
When func(payload *ParsePayload) bool
}
ZodCheckInternals contains the internal state and logic for a check.
func (*ZodCheckInternals) Zod ¶ added in v0.6.0
func (c *ZodCheckInternals) Zod() *ZodCheckInternals
Zod implements ZodCheck.
type ZodConfig ¶
type ZodConfig struct {
CustomError ZodErrorMap
LocaleError ZodErrorMap
}
ZodConfig represents global configuration for validation and error handling.
type ZodCustomParams ¶ added in v0.3.1
type ZodCustomParams = CustomParams
ZodCustomParams is a type alias for CustomParams.
type ZodErrorMap ¶
type ZodErrorMap func(ZodRawIssue) string
ZodErrorMap represents a function that maps raw issues to error messages.
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.
func (ZodIssue) DivisorValue ¶ added in v0.6.0
DivisorValue returns the divisor for not_multiple_of issues.
func (ZodIssue) ExpectedType ¶ added in v0.6.0
func (z ZodIssue) ExpectedType() (ZodTypeCode, bool)
ExpectedType returns the expected type for invalid_type issues.
func (ZodIssue) FormatName ¶ added in v0.6.0
FormatName returns the format for invalid_format issues.
func (*ZodIssue) MaxValue ¶ added in v0.6.0
MaxValue returns the maximum value and whether it is present.
func (*ZodIssue) MinValue ¶ added in v0.6.0
MinValue returns the minimum value and whether it is present.
func (ZodIssue) ReceivedType ¶ added in v0.6.0
func (z ZodIssue) ReceivedType() (ZodTypeCode, bool)
ReceivedType 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.
type ZodIssueInvalidType ¶
type ZodIssueInvalidType struct {
ZodIssueBase
Expected ZodTypeCode `json:"expected"` // Expected type name
Received ZodTypeCode `json:"received"` // Actual type name
}
ZodIssueInvalidType represents an invalid type error.
type ZodIssueInvalidValue ¶
type ZodIssueInvalidValue struct {
ZodIssueBase
Options []any `json:"options"` // List of valid options
}
ZodIssueInvalidValue represents an invalid value error.
type ZodModifier ¶ added in v0.11.7
type ZodModifier struct {
Kind ZodModifierKind
Value any
HasValue bool
Func func() any
}
ZodModifier records one fluent modifier application in call order.
type ZodModifierKind ¶ added in v0.11.7
type ZodModifierKind string
ZodModifierKind identifies an ordered fluent modifier.
const ( // ZodModifierOptional records an Optional modifier. ZodModifierOptional ZodModifierKind = "optional" // ZodModifierNilable records a Nilable modifier. ZodModifierNilable ZodModifierKind = "nilable" // ZodModifierNonOptional records a NonOptional modifier. ZodModifierNonOptional ZodModifierKind = "nonoptional" // ZodModifierDefault records a Default modifier. ZodModifierDefault ZodModifierKind = "default" // ZodModifierPrefault records a Prefault modifier. ZodModifierPrefault ZodModifierKind = "prefault" )
type ZodPipe ¶ added in v0.3.0
type ZodPipe[In, Out any] struct { // contains filtered or unexported fields }
ZodPipe validates input with a source schema, then passes the result through a target function for further processing. In is the input type for the source schema. Out is the output type from the target function.
func NewZodPipe ¶ added in v0.3.0
func NewZodPipe[In, Out any](source ZodType[In], target ZodType[any], fn func(In, *ParseContext) (Out, error)) *ZodPipe[In, Out]
NewZodPipe creates a pipeline schema that validates input with source, then passes the result through fn for further processing.
func (*ZodPipe[In, Out]) Internals ¶ added in v0.6.0
func (p *ZodPipe[In, Out]) Internals() *ZodTypeInternals
Internals returns the schema's internal configuration.
func (*ZodPipe[In, Out]) IsNilable ¶ added in v0.3.0
IsNilable reports whether this schema accepts nil values.
func (*ZodPipe[In, Out]) IsOptional ¶ added in v0.3.0
IsOptional reports whether this schema accepts missing values.
func (*ZodPipe[In, Out]) MustParse ¶ added in v0.3.0
func (p *ZodPipe[In, Out]) MustParse(input any, ctx ...*ParseContext) Out
MustParse validates through the pipeline, panicking on error.
func (*ZodPipe[In, Out]) Output ¶ added in v0.6.0
Output returns the target schema of this pipeline.
func (*ZodPipe[In, Out]) Parse ¶ added in v0.3.0
func (p *ZodPipe[In, Out]) Parse(input any, ctx ...*ParseContext) (out Out, _ error)
Parse validates input through the source schema, then applies the target function.
func (*ZodPipe[In, Out]) ParseAny ¶ added in v0.10.0
func (p *ZodPipe[In, Out]) ParseAny(input any, ctx ...*ParseContext) (any, error)
ParseAny validates through the pipeline and returns an untyped result.
func (*ZodPipe[In, Middle]) Pipe ¶ added in v0.3.0
Pipe chains this pipeline into another target schema.
func (*ZodPipe[In, Middle]) Transform ¶ added in v0.3.0
func (p *ZodPipe[In, Middle]) Transform(fn func(Middle, *RefinementContext) (any, error)) *ZodTransform[Middle, any]
Transform chains a transformation onto this pipeline's output.
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.
func (ZodRawIssue) Divisor ¶ added in v0.6.0
func (r ZodRawIssue) Divisor() any
Divisor returns the divisor value from properties.
func (ZodRawIssue) Expected ¶ added in v0.6.0
func (r ZodRawIssue) Expected() ZodTypeCode
Expected returns the expected value from properties.
func (ZodRawIssue) Format ¶ added in v0.6.0
func (r ZodRawIssue) Format() string
Format returns the format value from properties.
func (ZodRawIssue) Includes ¶ added in v0.6.0
func (r ZodRawIssue) Includes() string
Includes returns the includes value from properties.
func (ZodRawIssue) Inclusive ¶ added in v0.6.0
func (r ZodRawIssue) Inclusive() bool
Inclusive returns the inclusive flag from properties.
func (ZodRawIssue) Keys ¶ added in v0.6.0
func (r ZodRawIssue) Keys() []string
Keys returns the keys from properties.
func (ZodRawIssue) Maximum ¶ added in v0.6.0
func (r ZodRawIssue) Maximum() any
Maximum returns the maximum value from properties.
func (ZodRawIssue) Minimum ¶ added in v0.6.0
func (r ZodRawIssue) Minimum() any
Minimum returns the minimum value from properties.
func (ZodRawIssue) Origin ¶ added in v0.6.0
func (r ZodRawIssue) Origin() string
Origin returns the origin value from properties.
func (ZodRawIssue) Pattern ¶ added in v0.6.0
func (r ZodRawIssue) Pattern() string
Pattern returns the pattern value from properties.
func (ZodRawIssue) Prefix ¶ added in v0.6.0
func (r ZodRawIssue) Prefix() string
Prefix returns the prefix value from properties.
func (ZodRawIssue) Received ¶ added in v0.6.0
func (r ZodRawIssue) Received() ZodTypeCode
Received returns the received value from properties.
func (ZodRawIssue) Suffix ¶ added in v0.6.0
func (r ZodRawIssue) Suffix() string
Suffix returns the suffix value from properties.
func (ZodRawIssue) Values ¶ added in v0.6.0
func (r ZodRawIssue) Values() []any
Values returns the values from properties.
type ZodRefineFn ¶ added in v0.3.0
ZodRefineFn defines the signature for a type-safe refinement.
type ZodSchema ¶ added in v0.3.0
type ZodSchema interface {
// ParseAny validates input and returns an untyped result.
ParseAny(input any, ctx ...*ParseContext) (any, error)
// Internals provides access to the internal state of this schema.
Internals() *ZodTypeInternals
// IsOptional reports whether this schema accepts missing values.
IsOptional() bool
// IsNilable reports whether this schema accepts nil values.
IsNilable() bool
}
ZodSchema is the minimal non-generic runtime contract shared by all schemas.
It is intentionally limited to the capabilities required by dynamic runtime code paths:
- parse an untyped input
- inspect shared runtime flags
- access core internals used by the engine and registries
Fluent methods such as Describe/Meta/RefineAny and compile-time constrained methods such as StrictParse are intentionally not part of this boundary. Those capabilities live on typed schemas or on separate generic constraints.
func ConvertToZodSchema ¶ added in v0.3.0
ConvertToZodSchema converts a value to ZodSchema, 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 applies a transformation function to a validated value, potentially changing its type. In is the input type validated by the source schema. Out is the output type produced by the transformation function.
func NewZodTransform ¶ added in v0.3.0
func NewZodTransform[In, Out any](source ZodType[In], fn func(In, *RefinementContext) (Out, error)) *ZodTransform[In, Out]
NewZodTransform creates a transformation schema that validates input with source, then applies fn to produce a potentially different output type.
func (*ZodTransform[In, Out]) Inner ¶ added in v0.6.0
func (t *ZodTransform[In, Out]) Inner() ZodSchema
Inner returns the source schema that feeds into this transformation.
func (*ZodTransform[In, Out]) Internals ¶ added in v0.6.0
func (t *ZodTransform[In, Out]) Internals() *ZodTypeInternals
Internals returns the schema's internal configuration.
func (*ZodTransform[In, Out]) IsNilable ¶ added in v0.3.0
func (t *ZodTransform[In, Out]) IsNilable() bool
IsNilable reports whether this schema accepts nil values.
func (*ZodTransform[In, Out]) IsOptional ¶ added in v0.3.0
func (t *ZodTransform[In, Out]) IsOptional() bool
IsOptional reports whether this schema accepts missing values.
func (*ZodTransform[In, Out]) MustParse ¶ added in v0.3.0
func (t *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 (t *ZodTransform[In, Out]) Parse(input any, ctx ...*ParseContext) (out Out, _ error)
Parse validates input with the source schema, then applies the transformation. When input is nil and the source uses an outer default modifier, the default value is returned directly without running the transformation (Zod v4 semantics).
func (*ZodTransform[In, Out]) ParseAny ¶ added in v0.3.1
func (t *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 (t *ZodTransform[In, Middle]) Pipe(target ZodType[any]) *ZodPipe[Middle, any]
Pipe chains this transformation into a target schema for further validation.
func (*ZodTransform[In, Middle]) Transform ¶ added in v0.3.0
func (t *ZodTransform[In, Middle]) Transform(fn func(Middle, *RefinementContext) (any, error)) *ZodTransform[Middle, any]
Transform chains an additional transformation onto this one.
type ZodType ¶
type ZodType[T any] interface { ZodSchema // Parse validates the input and returns the typed result. Parse(input any, ctx ...*ParseContext) (T, error) // MustParse validates input and panics on error. MustParse(input any, ctx ...*ParseContext) T }
ZodType is the typed parsing contract layered on top of ZodSchema.
This is the boundary most concrete schema implementations satisfy. It keeps runtime parsing typed without forcing every dynamic code path to depend on compile-time constrained parsing or fluent chaining contracts.
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" ZodTypeNumber ZodTypeCode = "number" ZodTypeNaN ZodTypeCode = "nan" ZodTypeInteger ZodTypeCode = "integer" ZodTypeBigInt ZodTypeCode = "bigint" ZodTypeBool ZodTypeCode = "bool" ZodTypeDate ZodTypeCode = "date" ZodTypeNil ZodTypeCode = "nil" // Special types ZodTypeAny ZodTypeCode = "any" ZodTypeUnknown ZodTypeCode = "unknown" ZodTypeNever ZodTypeCode = "never" // Collection types ZodTypeArray ZodTypeCode = "array" ZodTypeSlice ZodTypeCode = "slice" ZodTypeTuple ZodTypeCode = "tuple" ZodTypeObject ZodTypeCode = "object" ZodTypeStruct ZodTypeCode = "struct" ZodTypeRecord ZodTypeCode = "record" ZodTypeMap ZodTypeCode = "map" ZodTypeSet ZodTypeCode = "set" // Composite types ZodTypeUnion ZodTypeCode = "union" ZodTypeXor ZodTypeCode = "xor" ZodTypeDiscriminated ZodTypeCode = "discriminated_union" ZodTypeIntersection ZodTypeCode = "intersection" // Special string types ZodTypeStringBool ZodTypeCode = "stringbool" // Function and lazy types ZodTypeFunction ZodTypeCode = "function" ZodTypeLazy ZodTypeCode = "lazy" // Value types ZodTypeLiteral ZodTypeCode = "literal" ZodTypeEnum ZodTypeCode = "enum" // Modifier types ZodTypeOptional ZodTypeCode = "optional" ZodTypeNilable ZodTypeCode = "nilable" ZodTypeDefault ZodTypeCode = "default" ZodTypePrefault ZodTypeCode = "prefault" // Processing types ZodTypePipeline ZodTypeCode = "pipeline" ZodTypeTransform ZodTypeCode = "transform" ZodTypePipe ZodTypeCode = "pipe" ZodTypeCustom ZodTypeCode = "custom" ZodTypeCheck ZodTypeCode = "check" ZodTypeRefine ZodTypeCode = "refine" // Network and format types ZodTypeIPv4 ZodTypeCode = "ipv4" ZodTypeIPv6 ZodTypeCode = "ipv6" ZodTypeCIDRv4 ZodTypeCode = "cidrv4" ZodTypeCIDRv6 ZodTypeCode = "cidrv6" ZodTypeEmail ZodTypeCode = "email" ZodTypeURL ZodTypeCode = "url" ZodTypeHostname ZodTypeCode = "hostname" ZodTypeMAC ZodTypeCode = "mac" ZodTypeE164 ZodTypeCode = "e164" // Time types ZodTypeTime ZodTypeCode = "time" // ISO 8601 format validation types ZodTypeIso ZodTypeCode = "iso" ZodTypeISODateTime ZodTypeCode = "iso_datetime" ZodTypeISODate ZodTypeCode = "iso_date" ZodTypeISOTime ZodTypeCode = "iso_time" ZodTypeISODuration ZodTypeCode = "iso_duration" // File and binary types ZodTypeFile ZodTypeCode = "file" // Numeric subtypes ZodTypeFloat32 ZodTypeCode = "float32" ZodTypeFloat64 ZodTypeCode = "float64" ZodTypeFloat ZodTypeCode = "float" ZodTypeInt ZodTypeCode = "int" ZodTypeInt8 ZodTypeCode = "int8" ZodTypeInt16 ZodTypeCode = "int16" ZodTypeInt32 ZodTypeCode = "int32" ZodTypeInt64 ZodTypeCode = "int64" ZodTypeUint ZodTypeCode = "uint" ZodTypeUint8 ZodTypeCode = "uint8" ZodTypeUint16 ZodTypeCode = "uint16" ZodTypeUint32 ZodTypeCode = "uint32" ZodTypeUint64 ZodTypeCode = "uint64" ZodTypeUintptr ZodTypeCode = "uintptr" ZodTypeComplex64 ZodTypeCode = "complex64" ZodTypeComplex128 ZodTypeCode = "complex128" ZodTypeNonOptional ZodTypeCode = "nonoptional" )
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
Checks []ZodCheck // Validation checks to apply
Parse func(payload *ParsePayload, ctx *ParseContext) *ParsePayload
// Core validation flags
Coerce bool
Optional bool
Nilable bool
NonOptional bool
ExactOptional bool
// Default/Prefault values
DefaultValue any
DefaultFunc func() any
PrefaultValue any
PrefaultFunc func() any
// Ordered fluent modifier applications.
Modifiers []ZodModifier
// Transform function
Transform func(any, *RefinementContext) (any, error)
// Optionality configuration
OptIn string
OptOut string
// Constructor and configuration
Constructor func(def *ZodTypeDef) ZodType[any]
Values map[any]struct{}
Pattern *regexp.Regexp
Error *ZodErrorMap
Bag map[string]any
}
ZodTypeInternals holds the complete configuration and state for any schema.
func (*ZodTypeInternals) AddCheck ¶ added in v0.3.0
func (z *ZodTypeInternals) AddCheck(check ZodCheck)
AddCheck adds a validation check.
func (*ZodTypeInternals) Clone ¶ added in v0.3.0
func (z *ZodTypeInternals) Clone() *ZodTypeInternals
Clone creates a deep copy of the internals for copy-on-write modifications. Deep copied: Checks slice, Values map, Bag map and values. Shared (immutable): function pointers, Pattern, Error.
func (*ZodTypeInternals) IsCoerce ¶ added in v0.2.2
func (z *ZodTypeInternals) IsCoerce() bool
IsCoerce reports whether type coercion is enabled.
func (*ZodTypeInternals) IsExactOptional ¶ added in v0.5.4
func (z *ZodTypeInternals) IsExactOptional() bool
IsExactOptional reports whether exact optional mode is enabled.
func (*ZodTypeInternals) IsNilable ¶ added in v0.2.2
func (z *ZodTypeInternals) IsNilable() bool
IsNilable reports whether nil values are allowed.
func (*ZodTypeInternals) IsNonOptional ¶ added in v0.3.0
func (z *ZodTypeInternals) IsNonOptional() bool
IsNonOptional reports whether the field is non-optional.
func (*ZodTypeInternals) IsOptional ¶ added in v0.2.2
func (z *ZodTypeInternals) IsOptional() bool
IsOptional reports whether the field is optional.
func (*ZodTypeInternals) NilInputUsesDefault ¶ added in v0.11.7
func (z *ZodTypeInternals) NilInputUsesDefault() bool
NilInputUsesDefault reports whether nil input is claimed by an outer default modifier.
func (*ZodTypeInternals) SetCoerce ¶ added in v0.2.2
func (z *ZodTypeInternals) SetCoerce(value bool)
SetCoerce enables type coercion.
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. Also sets Optional=true because ExactOptional implies Optional for absent key handling.
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.
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.