validator

package
v0.2.1 Latest Latest
Warning

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

Go to latest
Published: Dec 26, 2025 License: MIT Imports: 7 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ErrorTypeRequired      = "required"
	ErrorTypeType          = "type"
	ErrorTypeMinLength     = "min_length"
	ErrorTypeMaxLength     = "max_length"
	ErrorTypeMin           = "min"
	ErrorTypeMax           = "max"
	ErrorTypePattern       = "pattern"
	ErrorTypeEmail         = "email"
	ErrorTypeURL           = "url"
	ErrorTypeUUID          = "uuid"
	ErrorTypeEnum          = "enum"
	ErrorTypeUnique        = "unique"
	ErrorTypeCustom        = "custom"
	ErrorTypeModel         = "model"
	ErrorTypeUnknownField  = "unknown_field"
	ErrorTypeDiscriminator = "discriminator"
)

Common error types

Variables

This section is empty.

Functions

func Validate

func Validate[T any](data map[string]any) (*T, error)

Validate validates data against a struct type

func ValidateAtLeastOne

func ValidateAtLeastOne(fields ...string) func(any) error

ValidateAtLeastOne validates that at least one of the specified fields is non-zero

func ValidateConditionalRequired

func ValidateConditionalRequired(conditionField string, conditionValue any, requiredField string) func(any) error

ValidateConditionalRequired validates that a field is required based on another field's value

func ValidateDateRange

func ValidateDateRange(startField, endField string, message string) func(any) error

ValidateDateRange validates that start date is before end date

func ValidateDict

func ValidateDict[T any](ctx *ValidationContext, value any, valueValidator func(map[string]any) (*T, error)) (map[string]*T, error)

ValidateDict validates a dictionary with typed values

func ValidateDiscriminatedUnion

func ValidateDiscriminatedUnion(ctx *ValidationContext, value any, discriminator string, mapping map[string]reflect.Type) (any, error)

ValidateDiscriminatedUnion is a helper function to validate a discriminated union

func ValidateFieldMatch

func ValidateFieldMatch(field1, field2 string) func(any) error

ValidateFieldMatch validates that two fields match (e.g., password confirmation)

func ValidateList

func ValidateList[T any](ctx *ValidationContext, value any, itemValidator func(map[string]any) (*T, error)) ([]*T, error)

ValidateList validates a list of items with a given type

func ValidateModel

func ValidateModel(v any) error

ValidateModel runs model-level validation on a struct This is called after all field validations have passed

func ValidateMutuallyExclusive

func ValidateMutuallyExclusive(fields ...string) func(any) error

ValidateMutuallyExclusive validates that only one of the specified fields is set

func ValidateOptional

func ValidateOptional[T any](ctx *ValidationContext, value any, validator func(map[string]any) (*T, error)) (*T, error)

ValidateOptional validates an optional value

func ValidateStrict

func ValidateStrict[T any](data map[string]any) (*T, error)

ValidateStrict validates data in strict mode

func ValidateUnion

func ValidateUnion(ctx *ValidationContext, value any, types ...reflect.Type) (any, error)

ValidateUnion is a helper function to validate a union value

func ValidateWithValidator

func ValidateWithValidator[T any](v *Validator, data map[string]any) (*T, error)

ValidateWithValidator validates using a specific validator instance

Types

type DictOf

type DictOf struct {
	KeyType   reflect.Type
	ValueType reflect.Type
	Items     map[any]any
	MinItems  int
	MaxItems  int
}

DictOf creates a validator for a dictionary/map with specific key and value types

func NewDictOf

func NewDictOf(keyType, valueType any) *DictOf

NewDictOf creates a new dict validator

func (*DictOf) Get

func (d *DictOf) Get() map[any]any

Get returns the validated items

func (*DictOf) Validate

func (d *DictOf) Validate(ctx *ValidationContext, value any) error

Validate validates a dictionary value

func (*DictOf) WithMaxItems

func (d *DictOf) WithMaxItems(max int) *DictOf

WithMaxItems sets the maximum number of items

func (*DictOf) WithMinItems

func (d *DictOf) WithMinItems(min int) *DictOf

WithMinItems sets the minimum number of items

type DiscriminatedUnion

type DiscriminatedUnion struct {
	// Discriminator is the field name that determines the type
	Discriminator string

	// Mapping maps discriminator values to types
	Mapping map[string]reflect.Type

	// Value holds the actual validated value
	Value any

	// SelectedKey indicates which discriminator value was used
	SelectedKey string
}

DiscriminatedUnion represents a tagged union where the type is determined by a discriminator field (like a "type" or "kind" field) Example: Animal with discriminator "species" can be Dog or Cat

func NewDiscriminatedUnion

func NewDiscriminatedUnion(discriminator string, mapping map[string]any) *DiscriminatedUnion

NewDiscriminatedUnion creates a new discriminated union

func (*DiscriminatedUnion) Get

func (d *DiscriminatedUnion) Get() any

Get returns the validated value

func (*DiscriminatedUnion) GetKey

func (d *DiscriminatedUnion) GetKey() string

GetKey returns the selected discriminator key

func (*DiscriminatedUnion) Validate

func (d *DiscriminatedUnion) Validate(ctx *ValidationContext, value any) error

Validate validates the value as a discriminated union

type FieldValidatorConfig

type FieldValidatorConfig struct {
	Mode      ValidatorMode
	Validator ValidatorFunc
}

FieldValidatorConfig configures a field validator

func AfterValidatorFunc

func AfterValidatorFunc(fn func(*ValidationContext, any) (any, error)) FieldValidatorConfig

AfterValidatorFunc creates an after-validator from a function

func BeforeValidatorFunc

func BeforeValidatorFunc(fn func(*ValidationContext, any) (any, error)) FieldValidatorConfig

BeforeValidatorFunc creates a before-validator from a function

func WrapValidatorFunc

func WrapValidatorFunc(fn func(*ValidationContext, any, ValidatorFunc) (any, error)) FieldValidatorConfig

WrapValidatorFunc creates a wrap-validator from a function

type ListOf

type ListOf struct {
	ItemType reflect.Type
	Items    []any
	MinItems int
	MaxItems int
}

ListOf creates a validator for a list of items of a specific type Example: ListOf(User{}) validates []User

func NewListOf

func NewListOf(itemType any) *ListOf

NewListOf creates a new list validator

func (*ListOf) Get

func (l *ListOf) Get() []any

Get returns the validated items

func (*ListOf) Validate

func (l *ListOf) Validate(ctx *ValidationContext, value any) error

Validate validates a list value

func (*ListOf) WithMaxItems

func (l *ListOf) WithMaxItems(max int) *ListOf

WithMaxItems sets the maximum number of items

func (*ListOf) WithMinItems

func (l *ListOf) WithMinItems(min int) *ListOf

WithMinItems sets the minimum number of items

type ModelValidator

type ModelValidator interface {
	ValidateModel() error
}

ModelValidator is an interface for types that can validate themselves This allows for cross-field validation logic

type Optional

type Optional struct {
	Type     reflect.Type
	Value    any
	HasValue bool
}

Optional wraps a type to make it optional (can be nil)

func NewOptional

func NewOptional(itemType any) *Optional

NewOptional creates a new optional validator

func (*Optional) Get

func (o *Optional) Get() any

Get returns the value (may be nil)

func (*Optional) IsNone

func (o *Optional) IsNone() bool

IsNone returns true if the optional is nil

func (*Optional) IsSome

func (o *Optional) IsSome() bool

IsSome returns true if the optional has a value

func (*Optional) Validate

func (o *Optional) Validate(ctx *ValidationContext, value any) error

Validate validates an optional value

type Union

type Union struct {
	// Types holds the possible types for this union
	Types []reflect.Type

	// Value holds the actual validated value
	Value any

	// SelectedType indicates which type was selected (index into Types)
	SelectedType int
}

Union represents a type that can be one of several possible types Example: Union[string, int, bool] - value can be string, int, or bool

func NewUnion

func NewUnion(types ...any) *Union

NewUnion creates a new union type from a set of possible types

func (*Union) Get

func (u *Union) Get() any

Get returns the validated value

func (*Union) GetType

func (u *Union) GetType() int

GetType returns the selected type index

func (*Union) Validate

func (u *Union) Validate(ctx *ValidationContext, value any) error

Validate attempts to validate the value against each possible type Returns the first successful validation

type UnionField

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

UnionField is a helper for defining union fields in structs Use this in your struct tags to indicate a field is a union

func NewUnionField

func NewUnionField(types ...any) *UnionField

NewUnionField creates a new union field

func (*UnionField) Get

func (u *UnionField) Get() any

Get returns the current value

func (*UnionField) Set

func (u *UnionField) Set(value any)

Set sets the value after validation

func (*UnionField) UnmarshalJSON

func (u *UnionField) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler for union fields

type ValidationContext

type ValidationContext struct {
	// FieldName is the current field being validated
	FieldName string

	// FieldPath is the full path to the current field (for nested structures)
	FieldPath []string

	// ValidatedData contains fields that have already been validated
	// This allows validators to access other field values
	ValidatedData map[string]any

	// RawData is the original input data before validation
	RawData map[string]any

	// UserContext is custom context data provided by the user
	UserContext map[string]any

	// Mode indicates whether this is validation or serialization
	Mode ValidationMode

	// Parent is the parent context for nested validation
	Parent *ValidationContext
}

ValidationContext provides context information during validation

func NewValidationContext

func NewValidationContext() *ValidationContext

NewValidationContext creates a new validation context

func (*ValidationContext) GetFieldPathString

func (c *ValidationContext) GetFieldPathString() string

GetFieldPathString returns the field path as a dot-separated string

func (*ValidationContext) GetUserContextValue

func (c *ValidationContext) GetUserContextValue(key string) (any, bool)

GetUserContextValue retrieves a user context value

func (*ValidationContext) GetValidatedValue

func (c *ValidationContext) GetValidatedValue(key string) (any, bool)

GetValidatedValue retrieves a validated value from the context

func (*ValidationContext) SetUserContextValue

func (c *ValidationContext) SetUserContextValue(key string, value any)

SetUserContextValue sets a user context value

func (*ValidationContext) SetValidatedValue

func (c *ValidationContext) SetValidatedValue(key string, value any)

SetValidatedValue sets a validated value in the context

func (*ValidationContext) WithField

func (c *ValidationContext) WithField(fieldName string) *ValidationContext

WithField creates a child context for a specific field

func (*ValidationContext) WithMode

WithMode creates a new context with a different mode

type ValidationError

type ValidationError struct {
	Field      []string // Field path, e.g., ["user", "address", "zip"]
	Message    string   // Human-readable error message
	Type       string   // Machine-readable error type (e.g., "min_length", "email")
	Value      any      // The actual value that failed validation
	Constraint any      // The constraint that was violated (e.g., min=5)
}

ValidationError represents a single validation error

func NewFieldError

func NewFieldError(fieldName, message, errorType string, value, constraint any) ValidationError

NewFieldError creates a validation error for a specific field

func NewValidationError

func NewValidationError(field []string, message, errorType string, value, constraint any) ValidationError

NewValidationError creates a new validation error

func (*ValidationError) Error

func (v *ValidationError) Error() string

Error returns a formatted error message

type ValidationErrors

type ValidationErrors struct {
	Errors []ValidationError
}

ValidationErrors represents multiple validation errors

func (*ValidationErrors) Add

func (v *ValidationErrors) Add(err ValidationError)

Add adds a new validation error

func (*ValidationErrors) Error

func (v *ValidationErrors) Error() string

Error returns a formatted string of all validation errors

func (*ValidationErrors) HasErrors

func (v *ValidationErrors) HasErrors() bool

HasErrors returns true if there are any validation errors

func (*ValidationErrors) Merge

func (v *ValidationErrors) Merge(other *ValidationErrors)

Merge combines multiple ValidationErrors into one

func (*ValidationErrors) ToError

func (v *ValidationErrors) ToError() error

ToError converts ValidationErrors to error interface, or nil if no errors

func (*ValidationErrors) WithFieldPrefix

func (v *ValidationErrors) WithFieldPrefix(prefix string) *ValidationErrors

WithFieldPrefix adds a field prefix to all errors (for nested validation)

type ValidationMode

type ValidationMode string

ValidationMode represents the validation mode

const (
	// ModeValidation is for validating input data
	ModeValidation ValidationMode = "validation"
	// ModeSerialization is for validating output data
	ModeSerialization ValidationMode = "serialization"
)

type Validator

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

Validator handles struct validation based on tags

func New

func New() *Validator

New creates a new validator with default settings

func NewStrict

func NewStrict() *Validator

NewStrict creates a validator in strict mode (no type coercion)

type ValidatorFunc

type ValidatorFunc func(ctx *ValidationContext, value any) (any, error)

ValidatorFunc is a function that validates a value

type ValidatorMode

type ValidatorMode int

ValidatorMode represents when a validator runs

const (
	// BeforeValidator runs before type parsing/coercion
	BeforeValidator ValidatorMode = iota
	// AfterValidator runs after type parsing (most common)
	AfterValidator
	// WrapValidator wraps the validation process
	WrapValidator
)

type WithModelValidator

type WithModelValidator struct {
	Validator func(any) error
}

WithModelValidator wraps a validator function for use in validation

Jump to

Keyboard shortcuts

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