types

package
v3.0.7 Latest Latest
Warning

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

Go to latest
Published: May 12, 2026 License: MIT Imports: 19 Imported by: 0

Documentation

Overview

Package types provides the core validation engine types and rule system.

The types package contains the fundamental building blocks for the validation system including canonical rule representations, compilation of rules into executable validator functions, parsing of struct tags into rules, and rule type identifiers. It provides the unified AST (Abstract Syntax Tree) for validation rules, ensuring consistency between tag-based and builder-based validation. The package includes comprehensive regex safety measures and Unicode-aware string validation, and is designed to be extensible, allowing custom rule types to be registered and compiled through the plugin system.

Package types contains compiler helpers and rule primitives.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetGlobalSupportedTypes added in v3.0.3

func GetGlobalSupportedTypes() []string

GetGlobalSupportedTypes returns all globally registered types.

func IsGlobalTypeRegistered added in v3.0.3

func IsGlobalTypeRegistered(name string) bool

IsGlobalTypeRegistered checks if a type is registered globally.

func RegisterGlobalType added in v3.0.3

func RegisterGlobalType(name string, factory TypeValidatorFactory)

RegisterGlobalType registers a process-wide type in the global registry. Duplicate names overwrite earlier factories.

func RegisterRule

func RegisterRule(kind Kind, rc RuleCompiler)

RegisterRule registers a global custom Rule compiler. Call this at init.

func SplitTag added in v3.0.5

func SplitTag(tag string) []string

SplitTag splits a tag string by semicolons, respecting parentheses.

Types

type CompileOpts added in v3.0.5

type CompileOpts struct {
	CollectAll bool
}

CompileOpts tunes rule compilation without changing existing defaults.

type Compiler

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

Compiler compiles rules into validator functions.

func NewCompiler

func NewCompiler(t translator.Translator) *Compiler

NewCompiler creates a new compiler with the given translator.

func (*Compiler) Compile

func (c *Compiler) Compile(rules []Rule) ValidatorFunc

Compile compiles a slice of rules into a validator function.

func (*Compiler) CompileContext added in v3.0.5

func (c *Compiler) CompileContext(rules []Rule) ContextValidatorFunc

CompileContext compiles rules into a context-aware validator.

func (*Compiler) CompileContextE added in v3.0.5

func (c *Compiler) CompileContextE(rules []Rule) (ContextValidatorFunc, error)

CompileContextE compiles rules into a context-aware validator.

func (*Compiler) CompileContextWithOpts added in v3.0.5

func (c *Compiler) CompileContextWithOpts(rules []Rule, opts CompileOpts) ContextValidatorFunc

CompileContextWithOpts compiles rules into a context-aware validator with options and converts compile errors into validation errors.

func (*Compiler) CompileContextWithOptsE added in v3.0.5

func (c *Compiler) CompileContextWithOptsE(rules []Rule, opts CompileOpts) (ContextValidatorFunc, error)

CompileContextWithOptsE compiles rules into a context-aware validator with options.

func (*Compiler) CompileE added in v3.0.5

func (c *Compiler) CompileE(rules []Rule) (ValidatorFunc, error)

CompileE compiles a slice of rules into a validator function and returns compile-time custom-rule errors to callers that need to fail early.

func (*Compiler) CompileField

func (c *Compiler) CompileField(rules []Rule) FieldValidator

CompileField compiles rules for struct field validation.

func (*Compiler) CompileWithOpts added in v3.0.5

func (c *Compiler) CompileWithOpts(rules []Rule, opts CompileOpts) ValidatorFunc

CompileWithOpts compiles rules with options and converts compile errors into validation errors for compatibility with Compile.

func (*Compiler) CompileWithOptsE added in v3.0.5

func (c *Compiler) CompileWithOptsE(rules []Rule, opts CompileOpts) (ValidatorFunc, error)

CompileWithOptsE compiles a slice of rules with options.

func (*Compiler) RegisterContextRule added in v3.0.5

func (c *Compiler) RegisterContextRule(kind Kind, rc ContextRuleCompiler)

RegisterContextRule registers a context-aware custom rule compiler for this compiler instance. It is used only by context-aware compile APIs.

func (*Compiler) RegisterRule

func (c *Compiler) RegisterRule(kind Kind, rc RuleCompiler)

RegisterRule registers a custom rule compiler for this compiler instance.

func (*Compiler) RegisterType added in v3.0.5

func (c *Compiler) RegisterType(name string, factory TypeValidatorFactory)

RegisterType registers a custom type validator for this compiler instance.

func (*Compiler) SetTypeRegistry added in v3.0.5

func (c *Compiler) SetTypeRegistry(registry *TypeRegistry)

SetTypeRegistry sets per-compiler custom type validators.

func (*Compiler) T

func (c *Compiler) T(code string, defaultMsg string, params []any) string

T returns a translated message for the given code, or defaultMsg if no translator or translation is available. This is a public proxy to enable external validator plugins to use the compiler's translator.

type ContextRuleCompiler added in v3.0.5

type ContextRuleCompiler func(c *Compiler, rule Rule) (ContextValidatorFunc, error)

ContextRuleCompiler compiles one Rule into a context-aware validator.

type ContextValidatorFunc added in v3.0.5

type ContextValidatorFunc func(ctx context.Context, v any) error

ContextValidatorFunc represents a compiled context-aware validation function.

type FieldValidator

type FieldValidator func(field any) error

FieldValidator represents a field-specific validation function.

type Kind

type Kind string

Kind represents the type of validation rule.

This type is used to identify different validation rule types in the AST.

const (
	// String validation kinds
	KString      Kind = "string"
	KLength      Kind = "length"
	KMinLength   Kind = "minLength"
	KMaxLength   Kind = "maxLength"
	KRegex       Kind = "regex"
	KOneOf       Kind = "oneOf"
	KMinRunes    Kind = "minRunes"
	KMaxRunes    Kind = "maxRunes"
	KNonEmpty    Kind = "nonEmpty"
	KContains    Kind = "contains"
	KNotContains Kind = "notContains"
	KPrefix      Kind = "prefix"
	KSuffix      Kind = "suffix"
	KURL         Kind = "url"
	KHostname    Kind = "hostname"
	KIP          Kind = "ip"
	KIPv4        Kind = "ipv4"
	KIPv6        Kind = "ipv6"
	KCIDR        Kind = "cidr"
	KASCII       Kind = "ascii"
	KAlpha       Kind = "alpha"
	KAlnum       Kind = "alnum"

	// Generic modifiers
	KOmitempty Kind = "omitempty"
	KRequired  Kind = "required"

	// Integer validation kinds
	KInt              Kind = "int"
	KInt64            Kind = "int64"
	KMinInt           Kind = "minInt"
	KMaxInt           Kind = "maxInt"
	KFloat            Kind = "float"
	KMinNumber        Kind = "minNumber"
	KMaxNumber        Kind = "maxNumber"
	KGreaterThan      Kind = "greaterThan"
	KGreaterThanEqual Kind = "greaterThanEqual"
	KLessThan         Kind = "lessThan"
	KLessThanEqual    Kind = "lessThanEqual"
	KBetween          Kind = "between"
	KPositive         Kind = "positive"
	KNonNegative      Kind = "nonNegative"
	KFinite           Kind = "finite"

	// Slice validation kinds
	KSlice          Kind = "slice"
	KSliceLength    Kind = "sliceLength"
	KMinSliceLength Kind = "minSliceLength"
	KMaxSliceLength Kind = "maxSliceLength"
	KForEach        Kind = "forEach"
	KSliceUnique    Kind = "sliceUnique"
	KSliceContains  Kind = "sliceContains"

	// Array validation kinds
	KArray          Kind = "array"
	KArrayLength    Kind = "arrayLength"
	KMinArrayLength Kind = "minArrayLength"
	KMaxArrayLength Kind = "maxArrayLength"
	KArrayForEach   Kind = "arrayForEach"
	KArrayUnique    Kind = "arrayUnique"
	KArrayContains  Kind = "arrayContains"

	// Map validation kinds
	KMap        Kind = "map"
	KMapLength  Kind = "mapLength"
	KMinMapKeys Kind = "minMapKeys"
	KMaxMapKeys Kind = "maxMapKeys"
	KMapKeys    Kind = "mapKeys"
	KMapValues  Kind = "mapValues"

	// Boolean validation kinds
	KBool      Kind = "bool"
	KBoolTrue  Kind = "boolTrue"
	KBoolFalse Kind = "boolFalse"

	// Time validation kinds
	KTime        Kind = "time"
	KTimeNotZero Kind = "timeNotZero"
	KTimeBefore  Kind = "timeBefore"
	KTimeAfter   Kind = "timeAfter"
	KTimeBetween Kind = "timeBetween"
)

type Rule

type Rule struct {
	Kind Kind
	Args map[string]any // e.g. {"n": int64(3), "pattern": ".*"}
	Elem *Rule          // For nested rules (e.g., slice element validation)
}

Rule represents a single validation rule with its arguments.

Fields:

  • Kind: The type of validation rule.
  • Args: Map of rule-specific arguments (e.g., {"n": int64(3), "pattern": ".*"}).
  • Elem: For nested rules (e.g., slice element validation).

func NewRule

func NewRule(kind Kind, args map[string]any) Rule

NewRule creates a new rule with the given kind and arguments.

func NewRuleWithElem

func NewRuleWithElem(kind Kind, args map[string]any, elem *Rule) Rule

NewRuleWithElem builds a Rule with an element sub-rule for nesting.

func NewRuleWithElemValue deprecated

func NewRuleWithElemValue(kind Kind, args map[string]any, elem Rule) Rule

Deprecated: use NewRuleWithElem(kind, args, &elem) directly when you need to pass a value. This variant was kept for compatibility and will be removed in a future version.

func ParseTag

func ParseTag(tag string) ([]Rule, error)

ParseTag parses a struct tag string into a slice of rules using global custom type registrations.

func ParseTagWithRegistry added in v3.0.5

func ParseTagWithRegistry(tag string, registry *TypeRegistry) ([]Rule, error)

ParseTagWithRegistry parses a struct tag string with an optional per-instance custom type registry. Per-instance types are checked before global types. Example: "string;min=3;max=50" -> []Rule

type RuleCompiler

type RuleCompiler func(c *Compiler, rule Rule) (func(any) error, error)

RuleCompiler compiles a single Rule into a validate function. Implementations may precompute heavy state (e.g., compiled regex).

type TypeRegistry added in v3.0.3

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

TypeRegistry manages custom type validators and provides a way to register and retrieve type validators without the core engine knowing about specific types.

func NewTypeRegistry added in v3.0.3

func NewTypeRegistry() *TypeRegistry

NewTypeRegistry creates a new type registry.

func (*TypeRegistry) Clone added in v3.0.5

func (r *TypeRegistry) Clone() *TypeRegistry

Clone returns an independent copy of the registry.

func (*TypeRegistry) GetSupportedTypes added in v3.0.3

func (r *TypeRegistry) GetSupportedTypes() []string

GetSupportedTypes returns a list of all registered custom types.

func (*TypeRegistry) GetTypeValidator added in v3.0.3

func (r *TypeRegistry) GetTypeValidator(name string, translator translator.Translator) (TypeValidator, bool)

GetTypeValidator creates a new type validator instance for the given type.

func (*TypeRegistry) IsTypeRegistered added in v3.0.3

func (r *TypeRegistry) IsTypeRegistered(name string) bool

IsTypeRegistered checks if a type is registered.

func (*TypeRegistry) RegisterType added in v3.0.3

func (r *TypeRegistry) RegisterType(name string, factory TypeValidatorFactory)

RegisterType registers a type validator factory for a given type name.

type TypeValidator added in v3.0.3

type TypeValidator interface {
	// Validate validates a value of this custom type.
	Validate(value any) error
}

TypeValidator defines the interface for custom type validators. Custom types must implement this interface to be registered.

func GetGlobalTypeValidator added in v3.0.3

func GetGlobalTypeValidator(name string, translator translator.Translator) (TypeValidator, bool)

GetGlobalTypeValidator gets a type validator from the global registry.

type TypeValidatorFactory added in v3.0.3

type TypeValidatorFactory interface {
	// CreateValidator creates a new validator instance for this type.
	CreateValidator(translator translator.Translator) TypeValidator
}

TypeValidatorFactory creates type validators for a specific custom type.

type ValidatorFunc

type ValidatorFunc func(v any) error

ValidatorFunc represents a compiled validation function.

Jump to

Keyboard shortcuts

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