Documentation
¶
Overview ¶
Package criterio provides utilities for marking and handling validation errors.
Index ¶
- Variables
- func DurPositive(val time.Duration) error
- func Nest(field string, err error) error
- func NetCIDR(val string) error
- func NetHost(val string) error
- func NetIP(val string) error
- func NetIPv4(val string) error
- func NetIPv6(val string) error
- func NetPort(val int) error
- func NetPortStr(val string) error
- func New[T any](field string, validators ...Validator[T]) func(val T) error
- func NewAll[T any](field string, validators ...Validator[T]) func(val T) error
- func Required[T comparable](val T) error
- func Run[T any](field string, val T, validators ...Validator[T]) error
- func RunAll[T any](field string, val T, validators ...Validator[T]) error
- func StrAlpha(val string) error
- func StrAlphanumeric(val string) error
- func StrEmail(val string) error
- func StrLowercase(val string) error
- func StrNoWhitespace(val string) error
- func StrNotEmpty(val string) error
- func StrNumeric(val string) error
- func StrURL(val string) error
- func StrUUID(val string) error
- func StrUppercase(val string) error
- func ValidateSlice[T any](field string, items []T, validate func(T) error) error
- func ValidateStruct(validations ...error) error
- type FieldError
- type FieldErrors
- type FieldErrorsBuilder
- type Integer
- type SignedNumber
- type Validator
- func Between[T cmp.Ordered](low, high T) Validator[T]
- func DurBetween(low, high time.Duration) Validator[time.Duration]
- func DurMax(max time.Duration) Validator[time.Duration]
- func DurMin(min time.Duration) Validator[time.Duration]
- func MapKeys[K comparable, V any](validator Validator[K]) Validator[map[K]V]
- func MapLenBetween[K comparable, V any](low, high int) Validator[map[K]V]
- func MapLenMax[K comparable, V any](max int) Validator[map[K]V]
- func MapLenMin[K comparable, V any](min int) Validator[map[K]V]
- func MapNotEmpty[K comparable, V any]() Validator[map[K]V]
- func MapValues[K comparable, V any](validator Validator[V]) Validator[map[K]V]
- func Max[T cmp.Ordered](max T) Validator[T]
- func Min[T cmp.Ordered](min T) Validator[T]
- func MultipleOf[T Integer](n T) Validator[T]
- func Negative[T SignedNumber]() Validator[T]
- func NonZero[T SignedNumber]() Validator[T]
- func Not[T any](v Validator[T], msg string) Validator[T]
- func OneOf[T comparable](allowed ...T) Validator[T]
- func Or[T any](validators ...Validator[T]) Validator[T]
- func Positive[T SignedNumber]() Validator[T]
- func SkipIf[T any](condition bool, validators ...Validator[T]) Validator[T]
- func SliceEach[T any](validator Validator[T]) Validator[[]T]
- func SliceLenBetween[T any](low, high int) Validator[[]T]
- func SliceLenMax[T any](max int) Validator[[]T]
- func SliceLenMin[T any](min int) Validator[[]T]
- func SliceNotEmpty[T any]() Validator[[]T]
- func SliceUnique[T comparable]() Validator[[]T]
- func StrBetween(low, high int) Validator[string]
- func StrContains(substr string) Validator[string]
- func StrHasPrefix(prefix string) Validator[string]
- func StrHasSuffix(suffix string) Validator[string]
- func StrMatches(re *regexp.Regexp) Validator[string]
- func StrMax(max int) Validator[string]
- func StrMin(min int) Validator[string]
- func StrOneOf(allowed ...string) Validator[string]
- func TimeAfter(t time.Time) Validator[time.Time]
- func TimeBefore(t time.Time) Validator[time.Time]
- func TimeBetween(start, end time.Time) Validator[time.Time]
- func TimeFuture() Validator[time.Time]
- func TimePast() Validator[time.Time]
- func When[T any](condition bool, validators ...Validator[T]) Validator[T]
Constants ¶
This section is empty.
Variables ¶
var ( EmailRegex = regexp.MustCompile(`^[a-zA-Z0-9._%+\-]+@[a-zA-Z0-9.\-]+\.[a-zA-Z]{2,}$`) UUIDRegex = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`) AlphaRegex = regexp.MustCompile(`^[a-zA-Z]+$`) AlphanumericRegex = regexp.MustCompile(`^[a-zA-Z0-9]+$`) NumericRegex = regexp.MustCompile(`^[0-9]+$`) WhitespaceRegex = regexp.MustCompile(`\s`) )
Default regex patterns used by string validators. These can be modified to change validation behavior globally.
WARNING: Modifying these affects all validations application-wide. Concurrent modification is not thread-safe. If you need to customize patterns, do so at program initialization before any validation occurs.
var (
HostnameRegex = regexp.MustCompile(`^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)*[a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?$`)
)
Default regex patterns used by network validators. These can be modified to change validation behavior globally.
WARNING: Modifying these affects all validations application-wide. Concurrent modification is not thread-safe. If you need to customize patterns, do so at program initialization before any validation occurs.
Functions ¶
func DurPositive ¶
DurPositive validates that a duration is positive (greater than zero).
func Nest ¶
Nest prefixes all field errors with a parent field name using dot notation. Useful for nested struct validation to create paths like "address.street".
Non-FieldErrors errors are wrapped with the field name as context.
func NetHost ¶
NetHost validates that a string is a valid hostname. Uses HostnameRegex which can be modified to change validation globally.
func NetPortStr ¶
NetPortStr validates that a string represents a valid port number (1-65535).
func New ¶
New creates a reusable validator function for a specific field. Stops on the first validation failure.
func NewAll ¶
NewAll creates a reusable validator function for a specific field. Collects all validation failures.
func Required ¶
func Required[T comparable](val T) error
Required validates that a value is non-zero.
func Run ¶
Run executes validators against the value, stopping on the first failure. Returns nil if all validators pass, or a FieldErrors with the first failure.
func RunAll ¶
RunAll executes all validators against the value, collecting all failures. Returns nil if all validators pass, or a FieldErrors containing all failures.
func StrAlpha ¶
StrAlpha validates that a string contains only letters. Uses AlphaRegex which can be modified to change validation globally.
func StrAlphanumeric ¶
StrAlphanumeric validates that a string contains only letters and numbers. Uses AlphanumericRegex which can be modified to change validation globally.
func StrEmail ¶
StrEmail validates that a string is a valid email address. Uses EmailRegex which can be modified to change validation globally.
func StrLowercase ¶
StrLowercase validates that a string is all lowercase.
func StrNoWhitespace ¶
StrNoWhitespace validates that a string contains no whitespace. Uses WhitespaceRegex which can be modified to change validation globally.
func StrNotEmpty ¶
StrNotEmpty validates that a string is not empty or whitespace-only. Note: This trims whitespace before checking, so " " is considered empty. Use Required[string]() if you only want to reject the zero value "".
func StrNumeric ¶
StrNumeric validates that a string contains only digits. Uses NumericRegex which can be modified to change validation globally.
func StrURL ¶
StrURL validates that a string is a valid URL. Validates that the string can be parsed as a URL with a scheme and host.
func StrUUID ¶
StrUUID validates that a string is a valid UUID format. Uses UUIDRegex which can be modified to change validation globally.
func StrUppercase ¶
StrUppercase validates that a string is all uppercase.
func ValidateSlice ¶
ValidateSlice validates each element in a slice using the provided function. Errors are prefixed with bracket notation (e.g., "items[0].name: is required").
func ValidateStruct ¶
ValidateStruct combines multiple field validation results into a single error. Pass the results of Run/RunAll calls for each field.
Non-FieldErrors errors (e.g., from external libraries) are included with an empty field name. For proper field context, wrap external errors with Nest or use Run/RunAll.
Types ¶
type FieldError ¶
FieldError represents a validation error for a specific field.
func NewFieldError ¶
func NewFieldError(field string, err error) FieldError
NewFieldError creates a single FieldError.
func (FieldError) Error ¶
func (e FieldError) Error() string
Error returns the error message for this field error.
func (FieldError) Unwrap ¶
func (e FieldError) Unwrap() error
Unwrap returns the underlying error for use with errors.Is and errors.As.
type FieldErrors ¶
type FieldErrors []FieldError
FieldErrors is a collection of field validation errors that implements the error interface.
func NewFieldErrors ¶
func NewFieldErrors(field string, err error) FieldErrors
NewFieldErrors creates a new FieldErrors from a single field error.
func (FieldErrors) Error ¶
func (e FieldErrors) Error() string
Error returns a human-readable error message combining all field errors.
type FieldErrorsBuilder ¶
type FieldErrorsBuilder []FieldError
FieldErrorsBuilder is used to build a collection of field validation errors. It does not implement the error interface to prevent accidental returns without calling ToError().
func (FieldErrorsBuilder) Append ¶
func (b FieldErrorsBuilder) Append(field string, err error) FieldErrorsBuilder
Append adds a field error to the collection. Returns the updated FieldErrorsBuilder for convenient chaining.
Example usage:
var errs criterio.FieldErrorsBuilder
errs = errs.Append("name", errRequired)
errs = errs.Append("duration", errPositive)
return errs.ToError()
func (FieldErrorsBuilder) ToError ¶
func (b FieldErrorsBuilder) ToError() error
ToError converts FieldErrorsBuilder to an error. Returns nil if there are no errors, preventing the empty-slice-as-non-nil-error issue.
type Integer ¶
type Integer interface {
~int | ~int8 | ~int16 | ~int32 | ~int64 |
~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~uintptr
}
Integer is a constraint for all integer types.
type SignedNumber ¶
SignedNumber is a constraint for signed numeric types that can be negative.
type Validator ¶
Validator validates a value and returns an error if validation fails.
func Between ¶
Between returns a validator that checks if a value is between low and high (inclusive). Works with any ordered type (integers, floats, strings, etc.).
func DurBetween ¶
DurBetween returns a validator that checks if a duration is between low and high (inclusive).
func MapKeys ¶
func MapKeys[K comparable, V any](validator Validator[K]) Validator[map[K]V]
MapKeys returns a validator that applies a validator to each key in a map. Note: Map iteration order is non-deterministic in Go. When multiple keys fail validation, the error returned may vary between runs.
func MapLenBetween ¶
func MapLenBetween[K comparable, V any](low, high int) Validator[map[K]V]
MapLenBetween returns a validator that checks if a map length is between low and high (inclusive).
func MapLenMax ¶
func MapLenMax[K comparable, V any](max int) Validator[map[K]V]
MapLenMax returns a validator that checks if a map has at most max entries.
func MapLenMin ¶
func MapLenMin[K comparable, V any](min int) Validator[map[K]V]
MapLenMin returns a validator that checks if a map has at least min entries.
func MapNotEmpty ¶
func MapNotEmpty[K comparable, V any]() Validator[map[K]V]
MapNotEmpty returns a validator that checks if a map has at least one entry.
func MapValues ¶
func MapValues[K comparable, V any](validator Validator[V]) Validator[map[K]V]
MapValues returns a validator that applies a validator to each value in a map. Note: Map iteration order is non-deterministic in Go. When multiple values fail validation, the error returned may vary between runs.
func Max ¶
Max returns a validator that checks if a value is at most max. Works with any ordered type (integers, floats, strings, etc.).
func Min ¶
Min returns a validator that checks if a value is at least min. Works with any ordered type (integers, floats, strings, etc.).
func MultipleOf ¶
MultipleOf returns a validator that checks if a value is divisible by n. Works with integer types only. Panics if n is zero.
func Negative ¶
func Negative[T SignedNumber]() Validator[T]
Negative returns a validator that checks if a value is less than zero. Works with signed numeric types (integers and floats).
func NonZero ¶
func NonZero[T SignedNumber]() Validator[T]
NonZero returns a validator that checks if a value is not zero. Works with signed numeric types (integers and floats).
func Not ¶
Not returns a validator that inverts the result of another validator. Passes if the wrapped validator fails, fails if the wrapped validator passes.
func OneOf ¶
func OneOf[T comparable](allowed ...T) Validator[T]
OneOf returns a validator that checks if a value is one of the allowed values. Works with any comparable type. Automatically uses slice iteration for small sets (≤10) and map lookup for larger sets for optimal performance. Panics if no allowed values are provided.
func Or ¶
Or returns a validator that passes if any of the validators pass. Returns the last error if all validators fail. Panics if no validators are provided.
func Positive ¶
func Positive[T SignedNumber]() Validator[T]
Positive returns a validator that checks if a value is greater than zero. Works with signed numeric types (integers and floats).
func SkipIf ¶
SkipIf returns a validator that skips validation if the condition is true. If the condition is true, validation passes without running validators. Panics if no validators are provided.
func SliceLenBetween ¶
SliceLenBetween returns a validator that checks if a slice length is between low and high (inclusive).
func SliceLenMax ¶
SliceLenMax returns a validator that checks if a slice has at most max elements.
func SliceLenMin ¶
SliceLenMin returns a validator that checks if a slice has at least min elements.
func SliceNotEmpty ¶
SliceNotEmpty returns a validator that checks if a slice has at least one element.
func SliceUnique ¶
func SliceUnique[T comparable]() Validator[[]T]
SliceUnique returns a validator that checks if all elements in a slice are unique.
func StrBetween ¶
StrBetween returns a validator that checks if a string length is between low and high (inclusive). Counts characters (runes), not bytes.
func StrContains ¶
StrContains returns a validator that checks if a string contains a substring.
func StrHasPrefix ¶
StrHasPrefix returns a validator that checks if a string starts with a prefix.
func StrHasSuffix ¶
StrHasSuffix returns a validator that checks if a string ends with a suffix.
func StrMatches ¶
StrMatches returns a validator that checks if a string matches the provided regex.
func StrMax ¶
StrMax returns a validator that checks if a string has at most max characters (runes).
func StrMin ¶
StrMin returns a validator that checks if a string has at least min characters (runes).
func StrOneOf ¶
StrOneOf returns a validator that checks if a string is one of the allowed values. Automatically uses slice iteration for small sets (≤10) and map lookup for larger sets. Panics if no allowed values are provided.
func TimeBefore ¶
TimeBefore returns a validator that checks if a time is before a given time.
func TimeBetween ¶
TimeBetween returns a validator that checks if a time is between start and end (inclusive).
func TimeFuture ¶
TimeFuture returns a validator that checks if a time is in the future.