Documentation
¶
Index ¶
- Constants
- func Validate[T any](data map[string]any) (*T, error)
- func ValidateAtLeastOne(fields ...string) func(any) error
- func ValidateConditionalRequired(conditionField string, conditionValue any, requiredField string) func(any) error
- func ValidateDateRange(startField, endField string, message string) func(any) error
- func ValidateDict[T any](ctx *ValidationContext, value any, ...) (map[string]*T, error)
- func ValidateDiscriminatedUnion(ctx *ValidationContext, value any, discriminator string, ...) (any, error)
- func ValidateFieldMatch(field1, field2 string) func(any) error
- func ValidateList[T any](ctx *ValidationContext, value any, ...) ([]*T, error)
- func ValidateModel(v any) error
- func ValidateMutuallyExclusive(fields ...string) func(any) error
- func ValidateOptional[T any](ctx *ValidationContext, value any, validator func(map[string]any) (*T, error)) (*T, error)
- func ValidateStrict[T any](data map[string]any) (*T, error)
- func ValidateUnion(ctx *ValidationContext, value any, types ...reflect.Type) (any, error)
- func ValidateWithValidator[T any](v *Validator, data map[string]any) (*T, error)
- type DictOf
- type DiscriminatedUnion
- type FieldValidatorConfig
- type ListOf
- type ModelValidator
- type Optional
- type Union
- type UnionField
- type ValidationContext
- func (c *ValidationContext) GetFieldPathString() string
- func (c *ValidationContext) GetUserContextValue(key string) (any, bool)
- func (c *ValidationContext) GetValidatedValue(key string) (any, bool)
- func (c *ValidationContext) SetUserContextValue(key string, value any)
- func (c *ValidationContext) SetValidatedValue(key string, value any)
- func (c *ValidationContext) WithField(fieldName string) *ValidationContext
- func (c *ValidationContext) WithMode(mode ValidationMode) *ValidationContext
- type ValidationError
- type ValidationErrors
- func (v *ValidationErrors) Add(err ValidationError)
- func (v *ValidationErrors) Error() string
- func (v *ValidationErrors) HasErrors() bool
- func (v *ValidationErrors) Merge(other *ValidationErrors)
- func (v *ValidationErrors) ToError() error
- func (v *ValidationErrors) WithFieldPrefix(prefix string) *ValidationErrors
- type ValidationMode
- type Validator
- type ValidatorFunc
- type ValidatorMode
- type WithModelValidator
Constants ¶
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 ValidateAtLeastOne ¶
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 ¶
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 ¶
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 ¶
ValidateModel runs model-level validation on a struct This is called after all field validations have passed
func ValidateMutuallyExclusive ¶
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 ¶
ValidateStrict validates data in strict mode
func ValidateUnion ¶
ValidateUnion is a helper function to validate a union value
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 (*DictOf) Validate ¶
func (d *DictOf) Validate(ctx *ValidationContext, value any) error
Validate validates a dictionary value
func (*DictOf) WithMaxItems ¶
WithMaxItems sets the maximum number of items
func (*DictOf) WithMinItems ¶
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 ¶
ListOf creates a validator for a list of items of a specific type Example: ListOf(User{}) validates []User
func (*ListOf) Validate ¶
func (l *ListOf) Validate(ctx *ValidationContext, value any) error
Validate validates a list value
func (*ListOf) WithMaxItems ¶
WithMaxItems sets the maximum number of items
func (*ListOf) WithMinItems ¶
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 ¶
Optional wraps a type to make it optional (can be nil)
func NewOptional ¶
NewOptional creates a new optional validator
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
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) 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 ¶
func (c *ValidationContext) WithMode(mode ValidationMode) *ValidationContext
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
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 ¶
WithModelValidator wraps a validator function for use in validation