u

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Jun 3, 2025 License: MIT Imports: 3 Imported by: 0

Documentation

Overview

Package u provides a robust validation framework for Go.

Souuup is a flexible, type-safe validation library built with generics. It allows developers to validate complex data structures with nested fields and custom validation rules. The library provides detailed error reporting with exact locations of validation failures.

Basic Example:

schema := u.Schema{
	"username": u.Field("john doe", u.MinS(3), u.MaxS(20)),
	"age":      u.Field(25, u.MinN(18)),
}

s := u.NewSouuup(schema)
err := s.Validate()
if err != nil {
	fmt.Println("Validation failed:", err)
	return
}

The package is designed to be intuitive, composable, and extensible, making it suitable for a wide range of validation scenarios from simple form validation to complex API request validation.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type FieldDef

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

FieldDef represents a field with its value and validation rules. It implements the Validable interface, allowing it to be used in schemas.

func Field

func Field[T any](value T, rules ...Rule[T]) *FieldDef[T]

Field is the main function for creating a validatable field. It takes a value to validate, and a set of rules that will match the type of the given value.

Example:

// Validate a string with minimum and maximum length rules
nameField := u.Field("John Doe", u.MinS(2), u.MaxS(50))

// Validate a number with minimum value rule
ageField := u.Field(25, u.MinN(18))

// Validate using a custom rule
emailField := u.Field("[email protected]", func(fs u.FieldState[string]) error {
	if !strings.Contains(fs.Value, "@") {
		return fmt.Errorf("invalid email format")
	}
	return nil
})

func (FieldDef[T]) Errors

func (f FieldDef[T]) Errors() *ValidationError

Errors returns the validation errors associated with this field.

func (*FieldDef[T]) Validate

func (f *FieldDef[T]) Validate(ve *ValidationError, tag FieldTag)

Validate applies all rules to the field and adds any validation errors to the provided ValidationError object under the specified tag.

type FieldState

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

FieldState holds the value being validated and any validation errors. It is passed to validation rules to provide access to the value.

type FieldTag

type FieldTag = string

FieldTag represents the "key" of a field, and will be used to identify a field on an error map and schema

type FieldsErrorMap

type FieldsErrorMap = map[FieldTag]RuleErrors

FieldsErrorMap maps field tags to their validation errors. This is used to track which fields have validation errors and what those errors are.

type NestedErrorsMap

type NestedErrorsMap = map[FieldTag]*ValidationError

NestedErrorsMap maps field tags to nested validation error objects. This is used to represent hierarchical validation errors in nested structures.

type Numeric

type Numeric interface {
	constraints.Float | constraints.Integer
}

Numeric is a constraint that permits any numeric type: integer or float.

type NumericRule

type NumericRule[T Numeric] = Rule[T]

NumericRule is a specialised rule type for numeric validation.

type Rule

type Rule[T any] = func(FieldState[T]) error

Rule is a generic validation rule that takes a field state and returns an error if validation fails. It is the fundamental building block of the validation system.

type RuleError

type RuleError string

RuleError represents a single validation rule failure. It implements the error interface and contains the error message.

func (RuleError) Error

func (re RuleError) Error() string

Error returns the error message for a rule validation failure. This implementation satisfies the error interface.

type RuleErrors

type RuleErrors = []RuleError

RuleErrors represents a slice of rule validation failures for a single field.

type Schema

type Schema map[FieldTag]Validable

Schema is a map of field tags to validatable entities. It can contain both simple fields and nested schemas, allowing for the validation of complex, hierarchical data structures. Schema itself implements the Validable interface.

func (Schema) Errors

func (s Schema) Errors() *ValidationError

Errors returns all validation errors for this schema. It creates a new ValidationError, validates the schema against it, and returns the resulting errors.

func (Schema) Validate

func (s Schema) Validate(ve *ValidationError, _ FieldTag)

Validate implements the Validable interface for Schema. It validates all fields and nested schemas within the current schema, adding any validation errors to the provided ValidationError object.

type SliceRule

type SliceRule[T any] = Rule[[]T]

SliceRule is a specialised rule type for slice validation.

type Souuup

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

Souuup is the main validator instance. It holds a validation schema and internal state.

func NewSouuup

func NewSouuup(schema Schema) *Souuup

NewSouuup creates a new validator instance with the provided schema. This is the main entry point for setting up validation.

Example:

schema := u.Schema{
	"username": u.Field("johndoe", u.MinS(3)),
	"age":      u.Field(25, u.MinN(18)),
}
s := u.NewSouuup(schema)

func (*Souuup) Validate

func (s *Souuup) Validate() error

Validate performs validation against the schema and returns an error if validation fails. If validation succeeds, it returns nil.

Example:

err := s.Validate()
if err != nil {
	fmt.Println("Validation failed:", err)
	return
}

type StringRule

type StringRule = Rule[string]

StringRule is a specialised rule type for string validation.

type ToMapResult

type ToMapResult = map[FieldTag]map[string]any

ToMapResult is the type returned by ValidationError.ToMap(). It provides a serialisable representation of validation errors.

type Validable

type Validable interface {
	// Validate validates the entity against a ValidationError object
	// and associates any errors with the provided field tag.
	Validate(*ValidationError, FieldTag)

	// Errors returns any validation errors associated with this entity.
	Errors() *ValidationError
}

Validable is the interface that must be implemented by any validatable entity. It provides methods to validate the entity and retrieve validation errors. Both Schema and FieldDef implement this interface.

type ValidationError

type ValidationError struct {
	// Errors contains direct validation errors for fields at the current level
	Errors FieldsErrorMap

	// NestedErrors contains validation errors for nested fields/structures
	NestedErrors NestedErrorsMap

	// Parent points to the parent ValidationError in the tree, if any
	Parent *ValidationError
}

ValidationError represents the complete tree of validation errors. It tracks direct field errors and nested validation errors, forming a tree structure that matches the structure of the validated data.

func NewValidationError

func NewValidationError() *ValidationError

NewValidationError creates a new ValidationError with initialised maps. This helper prevents nil map errors when adding validation failures.

func (*ValidationError) AddError

func (ve *ValidationError) AddError(tag FieldTag, err error)

AddError adds a validation error for a specific field tag. The error is converted to a RuleError and appended to any existing errors for that field.

func (*ValidationError) Error

func (ve *ValidationError) Error() string

Error returns a JSON string representation of the validation errors. This implementation satisfies the error interface.

func (*ValidationError) GetOrCreateNested

func (ve *ValidationError) GetOrCreateNested(tag FieldTag) *ValidationError

GetOrCreateNested returns a nested ValidationError for a field, creating it if necessary. This is used when building up validation errors for nested structures.

func (*ValidationError) HasErrors

func (ve *ValidationError) HasErrors() bool

HasErrors returns true if there are any validation errors at any level in the tree. It recursively checks nested errors to determine if validation has failed anywhere.

func (*ValidationError) MarshalJSON

func (ve *ValidationError) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface for ValidationError. It creates a JSON representation of the validation errors using the ToMap method.

func (*ValidationError) ToMap

func (ve *ValidationError) ToMap() ToMapResult

ToMap converts a ValidationError to a map representation suitable for serialisation. It recursively processes the entire validation error tree and returns a flattened structure where field names are mapped to objects containing: - "errors": array of direct errors for the field - Other keys: nested validation structures

Example output structure:

{
  "username": {
    "errors": ["length is 2, but needs to be at least 3"]
  },
  "address": {
    "city": {
      "errors": ["cannot be empty"]
    }
  }
}

Jump to

Keyboard shortcuts

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