validator

package
v2.1.1 Latest Latest
Warning

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

Go to latest
Published: Aug 17, 2026 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

package validator provides Pydantic-inspired validation for Go.

Pedantigo offers two APIs: a Simple API for most use cases and a Validator API for advanced scenarios requiring custom options.

Global functions with automatic caching - no setup needed:

type User struct {
    Email string `json:"email" validate:"required,email"`
    Age   int    `json:"age" validate:"min=18,max=120"`
}

// Parse JSON and validate
user, err := vl.Unmarshal[User](jsonData)

// Create from JSON, map, or struct
user, err := vl.NewModel[User](input)

// Get cached JSON Schema
schema := vl.Schema[User]()

Validator API (Advanced)

For custom options like strict mode or extra field handling:

vl := validator.New[User](validator.Options{
    StrictMissingFields: true,
    ExtraFields:         validator.ExtraForbid,
})
user, err := vl.Unmarshal(jsonData)

Key Features

  • 100+ built-in validation constraints
  • JSON Schema generation with 240x caching speedup
  • Streaming validation for partial JSON (LLM support)
  • Discriminated unions with type-safe handling
  • Cross-field validation
  • Custom validator registration

See https://pedantigo.dev for complete documentation.

package validator provides Pydantic-inspired validation for Go.

Index

Constants

View Source
const (
	// ErrMsgFieldRequired is returned when a required field or value is missing.
	ErrMsgFieldRequired = "is required"

	// ErrMsgNilPointer is returned when Validate/StructPartial/StructExcept receives a nil pointer.
	ErrMsgNilPointer = "cannot validate nil pointer"

	// ErrMsgValueRequired is returned by Var when a required standalone value is missing.
	ErrMsgValueRequired = "value is required"

	// ErrMsgUnknownField is returned when ExtraForbid encounters unknown JSON fields.
	ErrMsgUnknownField = "unknown field in JSON"

	// ErrMsgEqMismatch is returned when a value doesn't match the expected value.
	ErrMsgEqMismatch = "must be equal to %s"

	// ErrMsgNeMismatch is returned when a value matches a forbidden value.
	ErrMsgNeMismatch = "must not be equal to %s"

	// ErrMsgMissingDiscriminator is returned when discriminator field is missing from JSON.
	ErrMsgMissingDiscriminator = "discriminator field %q is missing"

	// ErrMsgUnknownDiscriminator is returned when discriminator value doesn't match any variant.
	ErrMsgUnknownDiscriminator = "unknown discriminator value %q for field %q"

	// ErrMsgExtraFieldRequired is returned when ExtraAllow mode is enabled but no extra_fields field exists.
	ErrMsgExtraFieldRequired = "ExtraAllow mode requires a field with `pedantigo:\"extra_fields\"` tag of type map[string]any"
)

Error message constants for validation errors.

View Source
const DefaultTagName = "validate"

DefaultTagName is the default struct tag name used by Pedantigo. This is exported for reference but users should use GetTagName() for the current value.

Variables

This section is empty.

Functions

func Dict

func Dict[T any](obj *T) (map[string]interface{}, error)

Dict converts a struct into a map[string]interface{}. It uses a cached validator for type T, creating one if necessary.

Example:

user := &User{Email: "test@example.com", Age: 25}
dict, err := validator.Dict(user)
// dict["email"] == "test@example.com"
// dict["age"] == 25

func GetAlias

func GetAlias(name string) (string, bool)

GetAlias retrieves a registered alias expansion. Returns the expansion and true if found, empty string and false otherwise.

func GetTagName

func GetTagName() string

GetTagName returns the current global tag name. By default, this is "validate".

func Marshal

func Marshal[T any](obj *T) ([]byte, error)

Marshal validates and marshals a struct to JSON using default options. It uses a cached validator for type T, creating one if necessary.

Example:

user := &User{Email: "test@example.com", Age: 25}
jsonData, err := vl.Marshal(user)
if err != nil {
    // Handle validation or marshal error
}

func MarshalWithOptions

func MarshalWithOptions[T any](obj *T, opts MarshalOptions) ([]byte, error)

MarshalWithOptions validates and marshals a struct to JSON with custom options. Options allow context-based field exclusion and omitzero behavior. It uses a cached validator for type T, creating one if necessary.

Example:

user := &User{Email: "test@example.com", Password: "secret"}
opts := validator.ForContext("api") // Excludes password if tagged with exclude:api
jsonData, err := validator.MarshalWithOptions(user, opts)

func NewModel

func NewModel[T any](input any) (*T, error)

NewModel creates a validated instance of T from various input types. Accepts: []byte (JSON), T (struct), *T (pointer), or map[string]any (kwargs). It uses a cached validator for type T, creating one if necessary.

Example:

// From JSON bytes
user, err := vl.NewModel[User](jsonData)

// From map (kwargs pattern)
user, err := vl.NewModel[User](map[string]any{
    "email": "test@example.com",
    "age": 25,
})

// From existing struct (validates it)
existing := User{Email: "test@example.com"}
user, err := vl.NewModel[User](existing)

func RegisterAlias

func RegisterAlias(alias, expandsTo string) error

RegisterAlias registers a tag alias that expands to other tags. This allows creating shorthand names for common tag combinations.

Example:

validator.RegisterAlias("iscolor", "hexcolor|rgb|rgba|hsl|hsla")
// Now `iscolor` expands to an OR constraint for all color formats

validator.RegisterAlias("username", "required,alphanum,min=3,max=20")
// Now `username` expands to multiple constraints

Returns an error if the alias name conflicts with a built-in validator.

func RegisterStructValidation

func RegisterStructValidation[T any](fn StructLevelFunc[T]) error

RegisterStructValidation registers a struct-level validator for type T. The validator function will be called after field-level validation succeeds. Returns an error if the function is nil or if a validator is already registered for type T.

func RegisterTagNameFunc

func RegisterTagNameFunc(fn TagNameFunc)

RegisterTagNameFunc sets a custom function for resolving field names. This affects how field names appear in validation error messages.

Example:

validator.RegisterTagNameFunc(func(field reflect.StructField) string {
    if name := field.Tag.Get("form"); name != "" {
        return name
    }
    return field.Name
})

func RegisterValidation

func RegisterValidation(name string, fn ValidationFunc) error

RegisterValidation registers a custom field-level validator with the given name. The validator function will be called during validation for fields tagged with this name. Returns an error if the name is empty, the function is nil, or if the name conflicts with a built-in validator.

func RegisterValidationCtx

func RegisterValidationCtx(name string, fn ValidationFuncCtx) error

RegisterValidationCtx registers a context-aware custom validator. The validator will receive the context passed to ValidateCtx.

Example:

validator.RegisterValidationCtx("db_unique", func(ctx context.Context, value any, param string) error {
    db := ctx.Value("db").(*sql.DB)
    // Check uniqueness in database
    return nil
})

func RequireSingleRegisteredTagName added in v2.1.0

func RequireSingleRegisteredTagName(want string)

RequireSingleRegisteredTagName is called once by a framework plugin's setup. If a type was already Register()'d, it verifies the tag name matches want. If nothing has been Register()'d yet, it seeds want as the required tag name.

func Schema

func Schema[T any]() *jsonschema.Schema

Schema returns the JSON Schema for type T using a cached validator. The schema is cached within the validator for maximum performance.

Example:

schema := vl.Schema[User]()
// schema contains the full JSON Schema object

func SchemaJSON

func SchemaJSON[T any]() ([]byte, error)

SchemaJSON returns the JSON Schema for type T as JSON bytes. The schema is cached within the validator for maximum performance.

Example:

schemaBytes, err := validator.SchemaJSON[User]()
if err != nil {
    // Handle error
}

func SchemaJSONLLM

func SchemaJSONLLM[T any]() ([]byte, error)

SchemaJSONLLM returns a JSON Schema as JSON bytes optimized for LLM APIs. The $schema field is omitted because some LLMs (like Groq) echo it back in responses. Use this for: OpenAI function calling, Anthropic tool use, Claude structured outputs.

Example:

schemaBytes, err := validator.SchemaJSONLLM[User]()
if err != nil {
    // Handle error
}
// JSON output will NOT contain "$schema" field

func SchemaJSONOpenAPI

func SchemaJSONOpenAPI[T any]() ([]byte, error)

SchemaJSONOpenAPI returns an OpenAPI-compatible JSON Schema as JSON bytes. This version includes OpenAPI-specific enhancements like nullable support.

Example:

schemaBytes, err := validator.SchemaJSONOpenAPI[User]()
if err != nil {
    // Handle error
}

func SchemaLLM

func SchemaLLM[T any]() *jsonschema.Schema

SchemaLLM returns a JSON Schema optimized for LLM APIs (no $schema field). The schema is cached within the validator for maximum performance. Use this for: OpenAI function calling, Anthropic tool use, Claude structured outputs.

Example:

schema := validator.SchemaLLM[User]()
// schema contains the JSON Schema object without $schema field

func SchemaOpenAPI

func SchemaOpenAPI[T any]() *jsonschema.Schema

SchemaOpenAPI returns an OpenAPI-compatible JSON Schema for type T. This version includes OpenAPI-specific enhancements like nullable support.

Example:

schema := validator.SchemaOpenAPI[User]()
// Use in OpenAPI specification

func SetTagName

func SetTagName(name string)

SetTagName sets the global default struct tag name.

IMPORTANT: This function MUST be called in init() or at the very start of main(), BEFORE any other Pedantigo functions are called. Calling it after any validator has been created will cause a panic.

This allows Pedantigo to be used with existing struct tags from other validation libraries like go-playground/validator.

Example:

func init() {
    validator.SetTagName("validate") // Now uses `validate:"required,email"`
}

type User struct {
    Email string `json:"email" validate:"required,email"`
}

func Unmarshal

func Unmarshal[T any](data []byte) (*T, error)

Unmarshal unmarshals JSON data into a validated struct of type T. It uses a cached validator for type T, creating one if necessary. This is equivalent to calling New[T]().Unmarshal(data) but with automatic caching.

Example:

user, err := vl.Unmarshal[User](jsonData)
if err != nil {
    // Handle validation errors
}

func UnmarshalCtx

func UnmarshalCtx[T any](ctx context.Context, data []byte) (*T, error)

UnmarshalCtx unmarshals and validates with context. It uses a cached validator for type T, creating one if necessary. This allows context-aware validators to access the context during unmarshal.

Example:

ctx := context.WithValue(context.Background(), "db", dbConn)
user, err := validator.UnmarshalCtx[User](ctx, jsonData)
if err != nil {
    // Handle validation errors
}

func UnmarshalInto

func UnmarshalInto(data []byte, target any) error

UnmarshalInto unmarshals JSON data into the target using the cached validator for target's type. target must be a non-nil pointer to a struct whose type has been registered via Register() (which populates the validator cache).

If no validator is cached for target's type, UnmarshalInto panics with a message naming the missing type and the registration call needed.

This function enables framework integrations (Echo Binder, Gin middleware) where the target type is known only at runtime via reflect.Type, not at compile time via T.

Example:

var _ = validator.Register(validator.New[MyRequest]())  // register at init time

// later, at runtime:
var req MyRequest
err := validator.UnmarshalInto(jsonBody, &req)

func Validate

func Validate[T any](obj *T) error

Validate validates an existing struct using cached validators. This is equivalent to calling New[T]().Validate(obj) but with automatic caching.

Example:

user := &User{Email: "invalid"}
if err := vl.Validate(user); err != nil {
    // Handle validation errors
}

func ValidateCtx

func ValidateCtx[T any](ctx context.Context, obj *T) error

ValidateCtx validates with context support for context-aware validators. It uses a cached validator for type T, creating one if necessary. Context-aware validators registered with RegisterValidationCtx will receive the provided context.

Example:

ctx := context.WithValue(context.Background(), "db", dbConn)
user := &User{Username: "john"}
if err := validator.ValidateCtx(ctx, user); err != nil {
    // Handle validation errors
}

func ValidateExcept

func ValidateExcept[T any](obj *T, excludeFields ...string) error

ValidateExcept validates all fields except specified ones using cached validator. Field names should match JSON field names (from json tags). Excluded fields are skipped entirely.

Example:

user := &User{Email: "test@example.com", Age: 15}
// Validate all fields except age
err := validator.ValidateExcept(user, "age")

func ValidateInto added in v2.1.0

func ValidateInto(obj any) error

ValidateInto looks up the registered Validator[T] for obj's concrete type and validates it. obj must be a non-nil pointer — every real caller (Gin's binding functions populate the target via reflection, which requires addressability) already guarantees this, so a caller that violates it has a bug, and ValidateInto returns a clear error rather than silently reporting success. It does not panic (unlike UnmarshalInto's equivalent check), because the StructValidator interface this feeds into must never panic — returning a non-nil error is fully compatible with that contract.

Unlike UnmarshalInto, ValidateInto does not error when the pointed-to type was never registered — it returns nil, since this is called from framework validator adapters for every value they see, not just ones a caller deliberately registered via Register().

func ValidatePartial

func ValidatePartial[T any](obj *T, fields ...string) error

ValidatePartial validates only the specified fields using a cached validator. Field names should match JSON field names (from json tags). Fields not in the list are skipped entirely.

Example:

user := &User{Email: "invalid", Age: 15}
// Only validate email field, skip age validation
err := validator.ValidatePartial(user, "email")

func Var

func Var(value any, tag string) error

Var validates a single value against the provided constraints. This allows validating values without defining a struct.

Example:

err := validator.Var("test@example.com", "required,email")
err := validator.Var(25, "min=18,max=120")

Types

type ExtraFieldsMode

type ExtraFieldsMode int

ExtraFieldsMode controls how unknown JSON fields are handled during Unmarshal.

const (
	// ExtraIgnore ignores unknown JSON fields (default behavior).
	ExtraIgnore ExtraFieldsMode = iota
	// ExtraForbid rejects JSON with unknown fields.
	ExtraForbid
	// ExtraAllow stores unknown fields (reserved for future use).
	ExtraAllow
)

type FieldError

type FieldError struct {
	Field   string // Field path (e.g., "user.email")
	Code    string // Machine-readable error code (e.g., "INVALID_EMAIL")
	Message string // Human-readable error message
	Value   any    // The value that failed validation
}

FieldError represents a single field validation error.

type MarshalOptions

type MarshalOptions struct {
	// Context specifies which exclusion context to apply.
	// Fields tagged with validate:"exclude:context" will be omitted.
	// Empty string means no context-based exclusion.
	Context string

	// OmitZero controls whether fields with omitzero tag and zero values are omitted.
	// Default: true (honor omitzero tags)
	OmitZero bool
}

MarshalOptions configures Marshal behavior.

func DefaultMarshalOptions

func DefaultMarshalOptions() MarshalOptions

DefaultMarshalOptions returns sensible defaults.

func ForContext

func ForContext(ctx string) MarshalOptions

ForContext creates MarshalOptions for a specific exclusion context.

type Options

type Options struct {
	// StrictMissingFields controls whether missing fields without defaults are errors
	// When true (default): missing fields without defaults cause validation errors
	// When false: missing fields are left as zero values (user handles with pointers)
	StrictMissingFields bool

	// ExtraFields controls how unknown JSON fields are handled during Unmarshal.
	// Default is ExtraIgnore (unknown fields are silently ignored).
	ExtraFields ExtraFieldsMode

	// TagName overrides the global struct tag name for this validator instance.
	// If empty, the global tag name (set via SetTagName or defaulting to "validate") is used.
	// This allows different validators to use different struct tag names.
	//
	// Example:
	//   v := validator.New[User](validator.Options{TagName: "binding"})
	//   // This validator uses `binding:"required,email"` tags
	TagName string
}

Options configures validator behavior.

func DefaultOptions

func DefaultOptions() Options

DefaultOptions returns the default validator options.

type SecretBytes

type SecretBytes struct {
	// contains filtered or unexported fields
}

SecretBytes masks sensitive byte data in JSON output and logs. Use SecretBytes for binary secrets like encryption keys. The JSON input must be base64-encoded.

Example:

type Config struct {
    EncryptionKey SecretBytes `json:"encryption_key" validate:"required"`
}

func NewSecretBytes

func NewSecretBytes(b []byte) SecretBytes

NewSecretBytes creates a new SecretBytes from a byte slice.

func (SecretBytes) MarshalJSON

func (s SecretBytes) MarshalJSON() ([]byte, error)

MarshalJSON returns a masked value for JSON serialization.

func (SecretBytes) String

func (s SecretBytes) String() string

String returns a masked representation (safe for logs).

func (*SecretBytes) UnmarshalJSON

func (s *SecretBytes) UnmarshalJSON(data []byte) error

UnmarshalJSON stores the actual value from JSON input. Expects base64-encoded string in JSON.

func (SecretBytes) Value

func (s SecretBytes) Value() []byte

Value returns the actual secret bytes.

type SecretStr

type SecretStr struct {
	// contains filtered or unexported fields
}

SecretStr masks sensitive string data in JSON output and logs. Use SecretStr for passwords, API keys, tokens, and other sensitive data. The actual value is preserved internally and accessible via Value().

Example:

type Config struct {
    APIKey SecretStr `json:"api_key" validate:"required"`
}

// JSON output: {"api_key": "**********"}
// String() output: "**********"
// Value() output: actual API key

func NewSecretStr

func NewSecretStr(s string) SecretStr

NewSecretStr creates a new SecretStr from a plain string.

func (SecretStr) MarshalJSON

func (s SecretStr) MarshalJSON() ([]byte, error)

MarshalJSON returns a masked value for JSON serialization. The actual secret is never exposed in JSON output.

func (SecretStr) String

func (s SecretStr) String() string

String returns a masked representation (safe for logs). Implements fmt.Stringer interface.

func (*SecretStr) UnmarshalJSON

func (s *SecretStr) UnmarshalJSON(data []byte) error

UnmarshalJSON stores the actual value from JSON input. The value is preserved internally for later access via Value().

func (SecretStr) Value

func (s SecretStr) Value() string

Value returns the actual secret string value. Use this method to access the underlying secret for processing.

type StreamParser

type StreamParser[T any] struct {
	// contains filtered or unexported fields
}

StreamParser provides stateful parsing for streaming JSON chunks. Designed for LLM streaming APIs (Anthropic, OpenAI, etc.) Does NOT perform JSON repair - waits for complete valid JSON.

func NewStreamParser

func NewStreamParser[T any](opts ...Options) *StreamParser[T]

NewStreamParser creates a parser for streaming JSON.

func NewStreamParserWithValidator

func NewStreamParserWithValidator[T any](validator *Validator[T]) *StreamParser[T]

NewStreamParserWithValidator creates a parser with a custom validator. Use this for discriminated unions or when you need custom validator options.

func (*StreamParser[T]) Buffer

func (sp *StreamParser[T]) Buffer() []byte

Buffer returns the current accumulated buffer (for debugging).

func (*StreamParser[T]) Feed

func (sp *StreamParser[T]) Feed(chunk []byte) (*T, *StreamState, error)

Feed adds a new chunk of JSON data and returns the current state. Returns:

  • *T: Parsed struct (nil if JSON incomplete)
  • *StreamState: Completion state with tracking info
  • error: Validation errors (only when complete), or nil

func (*StreamParser[T]) Reset

func (sp *StreamParser[T]) Reset()

Reset clears the buffer and starts fresh.

type StreamState

type StreamState struct {
	// IsComplete is true if JSON parsing succeeded
	IsComplete bool

	// BytesReceived is the total bytes accumulated
	BytesReceived int

	// ParseAttempts tracks how many times parsing was attempted
	ParseAttempts int

	// LastError holds the most recent parse error (nil if complete)
	LastError error

	// PresentFields lists JSON field paths that were successfully parsed
	// Only populated when IsComplete is true
	PresentFields []string
}

StreamState tracks the parsing progress of streaming JSON.

func (*StreamState) HasField

func (ss *StreamState) HasField(path string) bool

HasField checks if a specific field path is present in the parsed result.

type StructLevelFunc

type StructLevelFunc[T any] func(obj *T) error

StructLevelFunc is the signature for struct-level validation functions. It receives the entire struct and returns an error if validation fails.

type TagNameFunc

type TagNameFunc func(field reflect.StructField) string

TagNameFunc is the signature for custom field name resolution.

type UnionOptions

type UnionOptions struct {
	// DiscriminatorField is the JSON field name used to determine the variant type.
	// For example: "type", "kind", "pet_type"
	DiscriminatorField string

	// Variants maps discriminator values to their corresponding Go types.
	Variants []UnionVariant
}

UnionOptions configures discriminated union behavior.

type UnionValidator

type UnionValidator[T any] struct {
	// contains filtered or unexported fields
}

UnionValidator validates discriminated unions where a field determines the variant type. Stub: not yet implemented.

func NewUnion

func NewUnion[T any](opts UnionOptions) (*UnionValidator[T], error)

NewUnion creates a UnionValidator for type T with discriminated union support. Stub: returns error indicating not implemented.

func (*UnionValidator[T]) Schema

func (v *UnionValidator[T]) Schema() *jsonschema.Schema

Schema generates JSON Schema for the discriminated union using oneOf. Returns a schema with oneOf array containing all variant schemas, each with a const constraint on the discriminator field. Implementation.

func (*UnionValidator[T]) Unmarshal

func (v *UnionValidator[T]) Unmarshal(data []byte) (any, error)

Unmarshal unmarshals JSON data into the appropriate union variant. Stub: returns error indicating not implemented.

func (*UnionValidator[T]) Validate

func (v *UnionValidator[T]) Validate(obj any) error

Validate validates a union value. Stub: returns error indicating not implemented.

type UnionVariant

type UnionVariant struct {
	// DiscriminatorValue is the value of the discriminator field that selects this variant.
	// For example, if discriminator is "type" and value is "cat", this variant handles {"type": "cat", ...}
	DiscriminatorValue string

	// Type is the Go struct type for this variant.
	Type reflect.Type
}

UnionVariant represents a variant type in a discriminated union. It maps a discriminator value to a specific Go struct type.

func VariantFor

func VariantFor[T any](discriminatorValue string) UnionVariant

VariantFor is a helper to create UnionVariant from a type parameter. Usage: VariantFor[Cat]("cat").

type Validatable

type Validatable interface {
	Validate() error
}

Validatable is an interface for types that implement custom validation. When a struct implements this interface, its Validate method is called after all field-level validations pass.

Example:

type DateRange struct {
    Start time.Time `json:"start" validate:"required"`
    End   time.Time `json:"end" validate:"required"`
}

func (d *DateRange) Validate() error {
    if d.End.Before(d.Start) {
        return errors.New("end must be after start")
    }
    return nil
}

type ValidationError

type ValidationError struct {
	Errors []FieldError
}

ValidationError represents one or more validation errors It implements the error interface for idiomatic Go error handling ValidationError represents an error condition.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error implements the error interface.

type ValidationFunc

type ValidationFunc func(value any, param string) error

ValidationFunc is the signature for custom field-level validation functions. It receives the field value and param string, returns an error if validation fails.

func GetCustomValidator

func GetCustomValidator(name string) (ValidationFunc, bool)

GetCustomValidator retrieves a registered custom validator by name. Returns the validator function and true if found, nil and false otherwise.

type ValidationFuncCtx

type ValidationFuncCtx func(ctx context.Context, value any, param string) error

ValidationFuncCtx is the signature for context-aware custom validators.

func GetContextValidator

func GetContextValidator(name string) (ValidationFuncCtx, bool)

GetContextValidator returns a registered context-aware validator by name. Returns (validator, true) if found, (nil, false) if not registered.

type Validator

type Validator[T any] struct {
	// contains filtered or unexported fields
}

Validator validates structs of type T.

func New

func New[T any](opts ...Options) *Validator[T]

New creates a new Validator for type T with optional configuration.

func Register

func Register[T any](v *Validator[T]) *Validator[T]

Register makes v the instance that framework-plugin binders (UnmarshalInto, the Echo Binder, etc.) will find for type T. Custom code that only ever calls v.Unmarshal() / v.Validate() directly never needs this.

Register may be called exactly once per type T. A second call for the same type — even with an identical instance — panics. Duplicate registration is the caller's responsibility to avoid; pedantigo enforces it rather than silently picking a winner, because a type may legitimately have multiple differently-configured validators (different Options), and only one of them can be "the" plugin-visible instance.

func (*Validator[T]) Dict

func (v *Validator[T]) Dict(obj *T) (map[string]interface{}, error)

Dict converts the object into a dict.

func (*Validator[T]) Marshal

func (v *Validator[T]) Marshal(obj *T) ([]byte, error)

Marshal validates and marshals struct to JSON.

func (*Validator[T]) MarshalWithOptions

func (v *Validator[T]) MarshalWithOptions(obj *T, opts MarshalOptions) ([]byte, error)

MarshalWithOptions validates and marshals struct to JSON with options. Options allow context-based field exclusion and omitzero behavior.

func (*Validator[T]) NewModel

func (v *Validator[T]) NewModel(input any) (*T, error)

NewModel creates a validated instance of T from various input types. Accepts: []byte (JSON), T (struct), *T (pointer), or map[string]any (kwargs). This is the unified constructor that validates regardless of input source.

func (*Validator[T]) Schema

func (v *Validator[T]) Schema() *jsonschema.Schema

Schema generates a JSON Schema from the validator's type T The schema includes all validation constraints mapped to JSON Schema properties Schema implements the method.

func (*Validator[T]) SchemaJSON

func (v *Validator[T]) SchemaJSON() ([]byte, error)

SchemaJSON generates JSON Schema as JSON bytes for LLM APIs Returns expanded schema with nested objects inlined (no $ref/$defs) Use this for: OpenAI function calling, Anthropic tool use, Claude structured outputs SchemaJSON implements the method.

func (*Validator[T]) SchemaJSONLLM

func (v *Validator[T]) SchemaJSONLLM() ([]byte, error)

SchemaJSONLLM generates JSON Schema as JSON bytes optimized for LLM APIs. Returns expanded schema with nested objects inlined (no $ref/$defs) and no $schema field. Use this for: OpenAI function calling, Anthropic tool use, Claude structured outputs.

Note: This has independent caching from SchemaJSON() to allow different optimizations.

func (*Validator[T]) SchemaJSONOpenAPI

func (v *Validator[T]) SchemaJSONOpenAPI() ([]byte, error)

SchemaJSONOpenAPI generates JSON Schema as JSON bytes for OpenAPI/Swagger specs. Returns schema with $ref/$defs for type reusability. Use this for: OpenAPI 3.0 specs, Swagger documentation, API documentation tools. SchemaJSONOpenAPI implements the method.

func (*Validator[T]) SchemaLLM

func (v *Validator[T]) SchemaLLM() *jsonschema.Schema

SchemaLLM generates a JSON Schema optimized for LLM APIs (no $schema field). Returns expanded schema with nested objects inlined (no $ref/$defs). The $schema field is omitted because some LLMs (like Groq) echo it back in responses. Use this for: OpenAI function calling, Anthropic tool use, Claude structured outputs.

Note: This has independent caching from Schema() to allow different optimizations.

func (*Validator[T]) SchemaOpenAPI

func (v *Validator[T]) SchemaOpenAPI() *jsonschema.Schema

SchemaOpenAPI generates a JSON Schema compatible with OpenAPI 3.1 specifications. Returns schema with $ref/$defs for type reusability and cleaner documentation.

Note: This generates a component schema (for use in components/schemas), not a complete OpenAPI document. Pedantigo is a validation library, not an API framework like Huma. Use this for: OpenAPI 3.1 specs, API documentation tools, embedding in OpenAPI documents. SchemaOpenAPI implements the method.

func (*Validator[T]) StructExcept

func (v *Validator[T]) StructExcept(obj *T, excludeFields ...string) error

StructExcept validates all fields except the specified ones. Excluded fields are skipped entirely. Field names should match JSON field names (from json tags).

func (*Validator[T]) StructPartial

func (v *Validator[T]) StructPartial(obj *T, fields ...string) error

StructPartial validates only the specified fields of a struct. Fields not in the list are skipped entirely. Field names should match JSON field names (from json tags).

func (*Validator[T]) Unmarshal

func (v *Validator[T]) Unmarshal(data []byte) (*T, error)

Unmarshal unmarshals JSON data, applies defaults, and validates.

func (*Validator[T]) UnmarshalCtx

func (v *Validator[T]) UnmarshalCtx(ctx context.Context, data []byte) (*T, error)

UnmarshalCtx unmarshals and validates with context. This allows context-aware validators to access the context during unmarshal.

func (*Validator[T]) Validate

func (v *Validator[T]) Validate(obj *T) error

Validate validates a struct and returns any validation errors NOTE: 'required' is NOT checked here - it's only checked during Unmarshal Validate checks if the value satisfies the constraint.

func (*Validator[T]) ValidateCtx

func (v *Validator[T]) ValidateCtx(ctx context.Context, obj *T) error

ValidateCtx validates with context support for context-aware validators. Context-aware validators registered with RegisterValidationCtx will receive the provided context, allowing them to access request-scoped values like database connections, authentication info, etc.

Directories

Path Synopsis
internal
constraints
Package constraints provides validation constraint types and builders for pedantigo.
Package constraints provides validation constraint types and builders for pedantigo.
isocodes
Package isocodes provides validation for ISO standard codes including country codes (ISO 3166-1), currency codes (ISO 4217), and postal codes.
Package isocodes provides validation for ISO standard codes including country codes (ISO 3166-1), currency codes (ISO 4217), and postal codes.
schemagen
Package schemagen provides JSON Schema generation and enhancement utilities for pedantigo validators.
Package schemagen provides JSON Schema generation and enhancement utilities for pedantigo validators.

Jump to

Keyboard shortcuts

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