validate

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 6, 2025 License: MIT Imports: 17 Imported by: 0

Documentation

Overview

Package validate defines immutable, strongly typed validators with structured errors, stable paths, aggregate and fail-fast calls, and typed localization. It can be used independently of the root shape package and never transforms.

Index

Examples

Constants

View Source
const (
	CodeTooSmall      = "too_small"
	CodeTooBig        = "too_big"
	CodeInvalidFormat = "invalid_format"
	CodeInvalidValue  = "invalid_value"
	CodeInvalidEnum   = "invalid_enum"
	CodeInvalidNumber = "invalid_number"
	CodeInvalidEmail  = "invalid_email"
	CodeInvalidURL    = "invalid_url"
	CodeInvalidUUID   = "invalid_uuid"
	CodeInvalidIP     = "invalid_ip"
	CodeTooDeep       = "too_deep"
	CodeTooManyIssues = "too_many_issues"
	CodeCustom        = "custom"
	// CodeUniqueLimit marks the deep-uniqueness resource bound, not a
	// data-validity verdict: the collection is valid but too large to compare
	// pairwise. It is deliberately distinct from CodeTooBig so a consumer
	// cannot confuse it with a Max length violation.
	CodeUniqueLimit = "unique_limit"
)
View Source
const (
	// English selects English built-in messages.
	English = validationlocale.English
	// SimplifiedChinese selects Simplified Chinese built-in messages.
	SimplifiedChinese = validationlocale.SimplifiedChinese
)
View Source
const DefaultMaxIssues = 100

DefaultMaxIssues bounds errors collected by exhaustive validation.

View Source
const MaxDeepUniqueItems = 1024

MaxDeepUniqueItems bounds the quadratic deep-equality path in Unique, which is taken when elements are not safely comparable with == (pointers, interfaces, and any type containing them). Collections above this size that need deep comparison report CodeUniqueLimit instead of being compared. Comparable collections use a hash set and are not bounded by this.

Variables

This section is empty.

Functions

func SetLanguage

func SetLanguage(lang Language)

SetLanguage changes the process-wide default message language.

func WithLocale

func WithLocale(ctx context.Context, lang Language) context.Context

WithLocale overrides the message language for operations using ctx.

Types

type Error

type Error struct {
	Issues []Issue `json:"issues"`
}

Error contains one or more validation issues.

func (*Error) Error

func (e *Error) Error() string

Error summarizes the validation failure.

type Issue

type Issue struct {
	Code     string `json:"code"`
	Path     Path   `json:"path"`
	Message  string `json:"message"`
	Label    string `json:"label,omitempty"`
	Expected any    `json:"expected,omitempty"`
	Received any    `json:"received,omitempty"`
	// contains filtered or unexported fields
}

Issue describes one validation failure and its structured location.

func (Issue) Error

func (i Issue) Error() string

Error formats the issue with its path.

type Language

type Language = validationlocale.Language

Language identifies a built-in validation-message language.

type MapKey

type MapKey interface {
	~string |
		~int | ~int8 | ~int16 | ~int32 | ~int64 |
		~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64
}

MapKey is the set of map key types supported by Map.

type MapValidator

type MapValidator[K MapKey, V any] struct {
	// contains filtered or unexported fields
}

MapValidator validates a map and each key and value in stable key order.

func Map

func Map[K MapKey, V any](key Validator[K], value Validator[V]) MapValidator[K, V]

Map creates a validator that checks keys and values in stable key order.

func (MapValidator[K, V]) And

func (v MapValidator[K, V]) And(vs ...Validator[map[K]V]) MapValidator[K, V]

And appends validators that run after this validator's rules.

func (MapValidator[K, V]) Label

func (v MapValidator[K, V]) Label(s string) MapValidator[K, V]

Label sets a parent label; key and value issues append their role.

func (MapValidator[K, V]) Len

func (v MapValidator[K, V]) Len(n int) MapValidator[K, V]

Len requires exactly n entries.

func (MapValidator[K, V]) Max

func (v MapValidator[K, V]) Max(n int) MapValidator[K, V]

Max allows at most n entries.

func (MapValidator[K, V]) Min

func (v MapValidator[K, V]) Min(n int) MapValidator[K, V]

Min requires at least n entries.

func (MapValidator[K, V]) NotEmpty

func (v MapValidator[K, V]) NotEmpty() MapValidator[K, V]

NotEmpty rejects nil and zero-length maps.

func (MapValidator[K, V]) NotNull

func (v MapValidator[K, V]) NotNull() MapValidator[K, V]

NotNull rejects nil maps.

func (MapValidator[K, V]) Refine

func (v MapValidator[K, V]) Refine(fns ...func(map[K]V) error) MapValidator[K, V]

Refine appends custom validation rules.

func (MapValidator[K, V]) RefineContext

func (v MapValidator[K, V]) RefineContext(fns ...func(context.Context, map[K]V) error) MapValidator[K, V]

RefineContext appends context-aware custom validation rules.

func (MapValidator[K, V]) Validate

func (v MapValidator[K, V]) Validate(x map[K]V) error

Validate collects issues using a background context.

func (MapValidator[K, V]) ValidateContext

func (v MapValidator[K, V]) ValidateContext(ctx context.Context, x map[K]V) error

ValidateContext collects issues and observes cancellation.

func (MapValidator[K, V]) ValidateFirst

func (v MapValidator[K, V]) ValidateFirst(x map[K]V) error

ValidateFirst stops after the first issue.

func (MapValidator[K, V]) ValidateFirstContext

func (v MapValidator[K, V]) ValidateFirstContext(ctx context.Context, x map[K]V) error

ValidateFirstContext stops after the first issue and observes cancellation.

type NumberValidator

type NumberValidator[N Numeric] struct {
	// contains filtered or unexported fields
}

NumberValidator validates values of a supported numeric type.

func Duration

func Duration() NumberValidator[types.Duration]

Duration creates a validator for types.Duration.

func Float64

func Float64() NumberValidator[float64]

Float64 creates a float64 validator.

func Int

func Int() NumberValidator[int]

Int creates an int validator.

func Int64

func Int64() NumberValidator[int64]

Int64 creates an int64 validator.

func Number

func Number[N Numeric]() NumberValidator[N]

Number creates a validator for a supported numeric type.

func (NumberValidator[N]) And

func (v NumberValidator[N]) And(vs ...Validator[N]) NumberValidator[N]

And appends validators that run after this validator's rules.

func (NumberValidator[N]) Between

func (v NumberValidator[N]) Between(a, b N) NumberValidator[N]

Between requires an inclusive value between a and b.

func (NumberValidator[N]) Gt

func (v NumberValidator[N]) Gt(n N) NumberValidator[N]

Gt requires a value strictly greater than n.

func (NumberValidator[N]) Gte

func (v NumberValidator[N]) Gte(n N) NumberValidator[N]

Gte requires a value greater than or equal to n.

func (NumberValidator[N]) Label

func (v NumberValidator[N]) Label(s string) NumberValidator[N]

Label sets the human-readable label on otherwise unlabeled issues.

func (NumberValidator[N]) Lt

func (v NumberValidator[N]) Lt(n N) NumberValidator[N]

Lt requires a value strictly less than n.

func (NumberValidator[N]) Lte

func (v NumberValidator[N]) Lte(n N) NumberValidator[N]

Lte requires a value less than or equal to n.

func (NumberValidator[N]) Max

func (v NumberValidator[N]) Max(n N) NumberValidator[N]

Max requires a value less than or equal to n.

func (NumberValidator[N]) Min

func (v NumberValidator[N]) Min(n N) NumberValidator[N]

Min requires a value greater than or equal to n.

func (NumberValidator[N]) Negative

func (v NumberValidator[N]) Negative() NumberValidator[N]

Negative requires a value less than zero.

func (NumberValidator[N]) NonNegative

func (v NumberValidator[N]) NonNegative() NumberValidator[N]

NonNegative requires a value greater than or equal to zero.

func (NumberValidator[N]) OneOf

func (v NumberValidator[N]) OneOf(values ...N) NumberValidator[N]

OneOf requires equality with one listed value.

func (NumberValidator[N]) Positive

func (v NumberValidator[N]) Positive() NumberValidator[N]

Positive requires a value greater than zero.

func (NumberValidator[N]) Refine

func (v NumberValidator[N]) Refine(fns ...func(N) error) NumberValidator[N]

Refine appends custom validation rules.

func (NumberValidator[N]) RefineContext

func (v NumberValidator[N]) RefineContext(fns ...func(context.Context, N) error) NumberValidator[N]

RefineContext appends context-aware custom validation rules.

func (NumberValidator[N]) Validate

func (v NumberValidator[N]) Validate(value N) error

Validate collects issues using a background context.

func (NumberValidator[N]) ValidateContext

func (v NumberValidator[N]) ValidateContext(ctx context.Context, value N) error

ValidateContext collects issues and observes cancellation.

func (NumberValidator[N]) ValidateFirst

func (v NumberValidator[N]) ValidateFirst(value N) error

ValidateFirst stops after the first issue.

func (NumberValidator[N]) ValidateFirstContext

func (v NumberValidator[N]) ValidateFirstContext(ctx context.Context, value N) error

ValidateFirstContext stops after the first issue and observes cancellation.

type Numeric

type Numeric interface {
	~int | ~int8 | ~int16 | ~int32 | ~int64 | ~uint | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~float32 | ~float64
}

Numeric is the set of supported signed, unsigned, and floating-point types.

type Path

type Path []PathSegment

Path locates a validation issue inside nested values.

func (Path) MarshalJSON

func (p Path) MarshalJSON() ([]byte, error)

MarshalJSON encodes fields and map keys as their values and indexes as numbers.

func (Path) String

func (p Path) String() string

String renders a Go-like field and collection path.

type PathKind

type PathKind uint8

PathKind identifies the kind of one validation path segment.

const (
	// PathField identifies a struct or object field.
	PathField PathKind = iota
	// PathIndex identifies a slice index.
	PathIndex
	// PathMapKey identifies a typed map key.
	PathMapKey
)

type PathSegment

type PathSegment struct {
	Kind   PathKind `json:"kind"`
	Key    string   `json:"key,omitempty"`
	Index  int      `json:"index,omitempty"`
	MapKey any      `json:"mapKey,omitempty"`
}

PathSegment is one field, slice index, or typed map key in a Path.

func FieldPath

func FieldPath(key string) PathSegment

FieldPath creates a field segment.

func IndexPath

func IndexPath(index int) PathSegment

IndexPath creates a slice-index segment.

func MapKeyPath

func MapKeyPath(key any) PathSegment

MapKeyPath creates a segment that preserves the concrete map-key value.

type PointerValidator

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

PointerValidator validates an optional *T and its non-nil value.

func Pointer

func Pointer[T any](inner Validator[T]) PointerValidator[T]

Pointer creates a validator for *T that applies inner to non-nil values.

func (PointerValidator[T]) And

func (v PointerValidator[T]) And(vs ...Validator[*T]) PointerValidator[T]

And appends validators that run after this validator's rules.

func (PointerValidator[T]) Label

func (v PointerValidator[T]) Label(s string) PointerValidator[T]

Label sets the human-readable label on otherwise unlabeled issues.

func (PointerValidator[T]) NotEmpty

func (v PointerValidator[T]) NotEmpty() PointerValidator[T]

NotEmpty rejects nil pointers.

func (PointerValidator[T]) NotNull

func (v PointerValidator[T]) NotNull() PointerValidator[T]

NotNull rejects nil pointers.

func (PointerValidator[T]) Refine

func (v PointerValidator[T]) Refine(fns ...func(*T) error) PointerValidator[T]

Refine appends custom validation rules.

func (PointerValidator[T]) RefineContext

func (v PointerValidator[T]) RefineContext(fns ...func(context.Context, *T) error) PointerValidator[T]

RefineContext appends context-aware custom validation rules.

func (PointerValidator[T]) Validate

func (v PointerValidator[T]) Validate(x *T) error

Validate collects issues using a background context.

func (PointerValidator[T]) ValidateContext

func (v PointerValidator[T]) ValidateContext(ctx context.Context, x *T) error

ValidateContext collects issues and observes cancellation.

func (PointerValidator[T]) ValidateFirst

func (v PointerValidator[T]) ValidateFirst(x *T) error

ValidateFirst stops after the first issue.

func (PointerValidator[T]) ValidateFirstContext

func (v PointerValidator[T]) ValidateFirstContext(ctx context.Context, x *T) error

ValidateFirstContext stops after the first issue and observes cancellation.

type SliceValidator

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

SliceValidator validates a slice and each of its elements.

func Slice

func Slice[T any](inner Validator[T]) SliceValidator[T]

Slice creates a validator that applies inner to each element.

func (SliceValidator[T]) And

func (v SliceValidator[T]) And(vs ...Validator[[]T]) SliceValidator[T]

And appends validators that run after this validator's rules.

func (SliceValidator[T]) Label

func (v SliceValidator[T]) Label(s string) SliceValidator[T]

Label sets the human-readable label on otherwise unlabeled issues.

func (SliceValidator[T]) Len

func (v SliceValidator[T]) Len(n int) SliceValidator[T]

Len requires exactly n elements.

func (SliceValidator[T]) Max

func (v SliceValidator[T]) Max(n int) SliceValidator[T]

Max allows at most n elements.

func (SliceValidator[T]) Min

func (v SliceValidator[T]) Min(n int) SliceValidator[T]

Min requires at least n elements.

func (SliceValidator[T]) NotEmpty

func (v SliceValidator[T]) NotEmpty() SliceValidator[T]

NotEmpty rejects nil and zero-length slices.

func (SliceValidator[T]) NotNull

func (v SliceValidator[T]) NotNull() SliceValidator[T]

NotNull rejects nil slices.

func (SliceValidator[T]) Refine

func (v SliceValidator[T]) Refine(fns ...func([]T) error) SliceValidator[T]

Refine appends custom validation rules.

func (SliceValidator[T]) RefineContext

func (v SliceValidator[T]) RefineContext(fns ...func(context.Context, []T) error) SliceValidator[T]

RefineContext appends context-aware custom validation rules.

func (SliceValidator[T]) Unique

func (v SliceValidator[T]) Unique() SliceValidator[T]

Unique rejects duplicate elements using value equality.

func (SliceValidator[T]) Validate

func (v SliceValidator[T]) Validate(x []T) error

Validate collects issues using a background context.

func (SliceValidator[T]) ValidateContext

func (v SliceValidator[T]) ValidateContext(ctx context.Context, x []T) error

ValidateContext collects issues and observes cancellation.

func (SliceValidator[T]) ValidateFirst

func (v SliceValidator[T]) ValidateFirst(x []T) error

ValidateFirst stops after the first issue.

func (SliceValidator[T]) ValidateFirstContext

func (v SliceValidator[T]) ValidateFirstContext(ctx context.Context, x []T) error

ValidateFirstContext stops after the first issue and observes cancellation.

type StringValidator

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

StringValidator validates strings with length, content, and format rules.

func String

func String() StringValidator

String creates a string validator.

Example
package main

import (
	"errors"
	"fmt"

	"github.com/rhevorn/shape/validate"
)

func main() {
	username := validate.String().NotEmpty().MinLength(3)
	err := username.Validate("")

	var validationError *validate.Error
	if errors.As(err, &validationError) {
		for _, issue := range validationError.Issues {
			fmt.Println(issue.Code, issue.Message)
		}
	}
}
Output:
invalid_value must not be empty
too_small must contain at least 3 characters

func (StringValidator) And

And appends validators that run after this validator's rules.

func (StringValidator) Contains

func (v StringValidator) Contains(x string) StringValidator

Contains requires substring x.

func (StringValidator) Email

func (v StringValidator) Email() StringValidator

Email requires one plain email mailbox address.

func (StringValidator) EndsWith

func (v StringValidator) EndsWith(x string) StringValidator

EndsWith requires suffix x.

func (StringValidator) IP

IP requires an IPv4 or IPv6 address.

func (StringValidator) Label

Label sets the human-readable label on otherwise unlabeled issues.

func (StringValidator) Len

Len requires exactly n Unicode code points.

func (StringValidator) MaxLength

func (v StringValidator) MaxLength(n int) StringValidator

MaxLength allows at most n Unicode code points.

func (StringValidator) MinLength

func (v StringValidator) MinLength(n int) StringValidator

MinLength requires at least n Unicode code points.

func (StringValidator) NotEmpty

func (v StringValidator) NotEmpty() StringValidator

NotEmpty rejects the empty string.

func (StringValidator) OneOf

func (v StringValidator) OneOf(values ...string) StringValidator

OneOf requires equality with one listed string.

func (StringValidator) Pattern

func (v StringValidator) Pattern(expr string) StringValidator

Pattern requires a match against the supplied Go regular expression.

func (StringValidator) Refine

func (v StringValidator) Refine(fns ...func(string) error) StringValidator

Refine appends custom validation rules.

func (StringValidator) RefineContext

func (v StringValidator) RefineContext(fns ...func(context.Context, string) error) StringValidator

RefineContext appends context-aware custom validation rules.

func (StringValidator) StartsWith

func (v StringValidator) StartsWith(x string) StringValidator

StartsWith requires prefix x.

func (StringValidator) URL

URL requires an absolute URL with a host.

func (StringValidator) UUID

UUID requires canonical hyphenated UUID syntax.

func (StringValidator) Validate

func (v StringValidator) Validate(value string) error

Validate collects issues using a background context.

func (StringValidator) ValidateContext

func (v StringValidator) ValidateContext(ctx context.Context, value string) error

ValidateContext collects issues and observes cancellation.

func (StringValidator) ValidateFirst

func (v StringValidator) ValidateFirst(value string) error

ValidateFirst stops after the first issue.

func (StringValidator) ValidateFirstContext

func (v StringValidator) ValidateFirstContext(ctx context.Context, value string) error

ValidateFirstContext stops after the first issue and observes cancellation.

type Validator

type Validator[T any] interface {
	Validate(T) error
	ValidateContext(context.Context, T) error
	ValidateFirst(T) error
	ValidateFirstContext(context.Context, T) error
}

Validator validates T either exhaustively or until the first issue.

type ValueValidator

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

ValueValidator validates any T with custom rules and composed validators.

func Bool

func Bool() ValueValidator[bool]

Bool creates a bool validator.

func Time

func Time() ValueValidator[time.Time]

Time creates a time.Time validator.

func Value

func Value[T any]() ValueValidator[T]

Value creates a validator for any T.

func (ValueValidator[T]) And

func (v ValueValidator[T]) And(vs ...Validator[T]) ValueValidator[T]

And appends validators that run after this validator's rules.

func (ValueValidator[T]) Label

func (v ValueValidator[T]) Label(s string) ValueValidator[T]

Label sets the human-readable label on otherwise unlabeled issues.

func (ValueValidator[T]) Refine

func (v ValueValidator[T]) Refine(fns ...func(T) error) ValueValidator[T]

Refine appends custom validation rules.

func (ValueValidator[T]) RefineContext

func (v ValueValidator[T]) RefineContext(fns ...func(context.Context, T) error) ValueValidator[T]

RefineContext appends context-aware custom validation rules.

func (ValueValidator[T]) Validate

func (v ValueValidator[T]) Validate(value T) error

Validate collects issues using a background context.

func (ValueValidator[T]) ValidateContext

func (v ValueValidator[T]) ValidateContext(ctx context.Context, value T) error

ValidateContext collects issues and observes cancellation.

func (ValueValidator[T]) ValidateFirst

func (v ValueValidator[T]) ValidateFirst(value T) error

ValidateFirst stops after the first issue.

func (ValueValidator[T]) ValidateFirstContext

func (v ValueValidator[T]) ValidateFirstContext(ctx context.Context, value T) error

ValidateFirstContext stops after the first issue and observes cancellation.

Jump to

Keyboard shortcuts

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