Documentation
¶
Overview ¶
Package validation provides typed, deterministic, bounded application validation without transport, binding, or persistence dependencies.
Index ¶
- Variables
- type AsyncValidator
- type AsyncValidatorFunc
- type Context
- type ContextError
- type ContextOption
- type InvalidError
- type Limits
- type Mode
- type Path
- type Presence
- type Report
- func (r Report) Add(violation Violation) Report
- func (r Report) ContextError() error
- func (r Report) Empty() bool
- func (r Report) Err() error
- func (r Report) HasCode(code string) bool
- func (r Report) HasErrors() bool
- func (r Report) Len() int
- func (r Report) Merge(other Report) Report
- func (r Report) String() string
- func (r Report) Truncated() bool
- func (r Report) Violations() []Violation
- type Segment
- type SegmentKind
- type Severity
- type Validator
- func All[T any](mode Mode, validators ...Validator[T]) Validator[T]
- func Any[T any](mode Mode, validators ...Validator[T]) Validator[T]
- func Dependent[T any](prerequisite, dependent Validator[T]) Validator[T]
- func IsolatePanics[T any](validator Validator[T]) Validator[T]
- func Not[T any](validator Validator[T]) Validator[T]
- func When[T any](predicate func(T) bool, then, otherwise Validator[T]) Validator[T]
- type ValidatorFunc
- type Value
- type Violation
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrInvalid marks a non-empty validation result containing errors. ErrInvalid = errors.New("validation failed") // ErrLimitExceeded marks rejected work that exceeded a configured bound. ErrLimitExceeded = errors.New("validation limit exceeded") // ErrInvalidLimit marks an invalid Limits configuration. ErrInvalidLimit = errors.New("invalid validation limit") // ErrValidatorPanic is the safe cause used for an isolated custom panic. ErrValidatorPanic = errors.New("validator panicked") // ErrInvalidViolation marks an unsafe or malformed custom diagnostic. ErrInvalidViolation = errors.New("invalid validation diagnostic") )
Functions ¶
This section is empty.
Types ¶
type AsyncValidator ¶
AsyncValidator is the separate contract for cancellation-aware I/O validation. Implementations are not deterministic Validator values.
func IsolateAsyncPanics ¶
func IsolateAsyncPanics[T any](validator AsyncValidator[T]) AsyncValidator[T]
IsolateAsyncPanics wraps an arbitrary asynchronous validator with the same secret-safe panic containment provided by AsyncValidatorFunc.
type AsyncValidatorFunc ¶
AsyncValidatorFunc adapts a context-aware function to AsyncValidator.
func (AsyncValidatorFunc[T]) ValidateAsync ¶
func (f AsyncValidatorFunc[T]) ValidateAsync( ctx context.Context, validationContext Context, value T, ) (report Report)
ValidateAsync calls the context-aware function.
type Context ¶
type Context struct {
// contains filtered or unexported fields
}
Context is immutable deterministic validation state. It intentionally does not embed context.Context because ordinary validators cannot perform I/O.
func NewContext ¶
func NewContext(limits Limits, options ...ContextOption) (Context, error)
NewContext constructs immutable validation state.
func (Context) Limits ¶
Limits returns the work limits. The zero-value Context uses DefaultLimits so validators fail closed without requiring construction for simple use.
type ContextError ¶ added in v1.1.0
type ContextError struct {
// contains filtered or unexported fields
}
ContextError is the structured terminal error returned by Report.Err.
Example ¶
package main
import (
"context"
"errors"
"fmt"
validation "github.com/faustbrian/go-validation"
validationjsonapi "github.com/faustbrian/go-validation/adapters/jsonapi"
)
func main() {
vctx, _ := validation.NewContext(validation.DefaultLimits())
ctx, cancel := context.WithCancel(context.Background())
cancel()
report := validation.AsyncAll[int](ctx, vctx, 1)
var terminal *validation.ContextError
if err := report.Err(); errors.As(err, &terminal) {
fmt.Println(terminal.Error())
} else {
_ = validationjsonapi.Errors(report)
}
}
Output: validation canceled
func (*ContextError) Error ¶ added in v1.1.0
func (e *ContextError) Error() string
Error returns a bounded context-terminal summary.
func (*ContextError) Report ¶ added in v1.1.0
func (e *ContextError) Report() Report
Report returns the immutable partial validation report.
func (*ContextError) Unwrap ¶ added in v1.1.0
func (e *ContextError) Unwrap() []error
Unwrap exposes stable context and validation error identities.
type ContextOption ¶
type ContextOption func(*contextConfig)
ContextOption configures NewContext.
func WithLocale ¶
func WithLocale(locale string) ContextOption
WithLocale records an application-defined locale identifier.
func WithMetadata ¶
func WithMetadata(key, value string) ContextOption
WithMetadata adds bounded non-sensitive metadata.
func WithOperation ¶
func WithOperation(operation string) ContextOption
WithOperation records an application-defined operation identifier.
type InvalidError ¶
type InvalidError struct {
// contains filtered or unexported fields
}
InvalidError exposes a validation report through errors.As.
Example ¶
package main
import (
"errors"
"fmt"
validation "github.com/faustbrian/go-validation"
"github.com/faustbrian/go-validation/rules"
)
func main() {
ctx, _ := validation.NewContext(validation.DefaultLimits())
err := rules.Email().Validate(ctx, "invalid").Err()
fmt.Println(errors.Is(err, validation.ErrInvalid))
}
Output: true
func (*InvalidError) Error ¶
func (e *InvalidError) Error() string
Error returns a value-safe summary.
func (*InvalidError) Report ¶
func (e *InvalidError) Report() Report
Report returns the immutable validation report.
func (*InvalidError) Unwrap ¶
func (e *InvalidError) Unwrap() error
Unwrap makes InvalidError compatible with errors.Is and ErrInvalid.
type Limits ¶
type Limits struct {
MaxDepth int
MaxCollectionSize int
MaxStringLength int
MaxViolations int
MaxPathLength int
MaxMetadataEntries int
MaxMetadataKeyLength int
MaxMetadataValueLength int
MaxRegexPatternLength int
MaxCustomConcurrency int
MaxStructFields int
MaxTagLength int
MaxCompiledPlans int
}
Limits bounds validation work performed on untrusted input.
func DefaultLimits ¶
func DefaultLimits() Limits
DefaultLimits returns conservative limits suitable for application input.
type Path ¶
type Path struct {
// contains filtered or unexported fields
}
Path is an immutable ordered location.
func (Path) JSONPointer ¶
JSONPointer serializes typed segments as RFC 6901 reference tokens. It does not evaluate the pointer or assign JSON Patch semantics to Item.
type Presence ¶
type Presence uint8
Presence represents whether an input was omitted, explicitly null, or set.
type Report ¶
type Report struct {
// contains filtered or unexported fields
}
Report is an immutable, ordered, deduplicated collection of violations with an optional context-terminal state.
func AsyncAll ¶
func AsyncAll[T any](ctx context.Context, validationContext Context, value T, validators ...AsyncValidator[T], ) Report
AsyncAll executes context-aware validators with bounded concurrency and merges their reports in declaration order. Cancellation stops unscheduled work; validators already running remain responsible for honoring ctx.
Example ¶
package main
import (
"context"
"fmt"
validation "github.com/faustbrian/go-validation"
)
func main() {
ctx, _ := validation.NewContext(validation.DefaultLimits())
check := validation.AsyncValidatorFunc[string](func(
_ context.Context, ctx validation.Context, _ string,
) validation.Report {
return validation.NewReport(ctx.Limits())
})
report := validation.AsyncAll(context.Background(), ctx, "user", check)
fmt.Println(report.Err() == nil)
}
Output: true
func ContextReport ¶ added in v1.1.0
ContextReport returns an empty report that snapshots ctx.Err(). An active context produces no terminal state.
func (Report) ContextError ¶ added in v1.1.0
ContextError reports the captured context terminal identity, if any.
func (Report) Err ¶
Err returns a typed error if validation did not complete or contains a blocking violation.
func (Report) HasErrors ¶
HasErrors reports whether any blocking violation was observed, including one omitted because MaxViolations was reached.
func (Report) Truncated ¶
Truncated reports whether a violation was omitted by the configured limit.
func (Report) Violations ¶
Violations returns a defensive copy preserving validation order.
type Segment ¶
type Segment struct {
// contains filtered or unexported fields
}
Segment is one typed path component.
type SegmentKind ¶
type SegmentKind uint8
SegmentKind distinguishes fields, collection indexes, keys, and items.
const ( // FieldSegment names an object field. FieldSegment SegmentKind = iota + 1 // IndexSegment identifies a collection index. IndexSegment // KeySegment identifies a map key. KeySegment // ItemSegment identifies the current collection item in a plan. ItemSegment )
type Validator ¶
Validator is the deterministic, side-effect-free validation contract.
Example ¶
package main
import (
"fmt"
validation "github.com/faustbrian/go-validation"
"github.com/faustbrian/go-validation/rules"
)
func main() {
ctx, _ := validation.NewContext(validation.DefaultLimits())
validator := validation.All(validation.CollectAll,
rules.RuneLength(3, 20), rules.Prefix("usr_"))
report := validator.Validate(ctx.WithPath(validation.Field("username")), "x")
for _, violation := range report.Violations() {
fmt.Println(violation.Path(), violation.Code())
}
}
Output: username rune_length username prefix
func Any ¶
Any requires at least one validator to pass. Failed alternatives are returned only when every alternative fails.
func IsolatePanics ¶
IsolatePanics explicitly wraps a custom validator with panic containment. The panic payload and rejected value are deliberately discarded.
type ValidatorFunc ¶
ValidatorFunc adapts an ordinary function to Validator.
func (ValidatorFunc[T]) Validate ¶
func (f ValidatorFunc[T]) Validate(ctx Context, value T) (report Report)
Validate calls the underlying validation function.
type Value ¶
type Value[T any] struct { // contains filtered or unexported fields }
Value preserves presence separately from a typed value.
Example ¶
package main
import (
"fmt"
validation "github.com/faustbrian/go-validation"
"github.com/faustbrian/go-validation/rules"
)
func main() {
ctx, _ := validation.NewContext(validation.DefaultLimits())
report := rules.Required[string]().Validate(ctx, validation.Missing[string]())
fmt.Println(report.HasCode("required"))
}
Output: true
func (Value[T]) IsEmpty ¶
IsEmpty reports whether a present string, collection, or map has length zero. Other values are empty when they are their Go zero value.
type Violation ¶
type Violation struct {
// contains filtered or unexported fields
}
Violation is a value-safe machine-readable validation finding.
func NewViolation ¶
func NewViolation(path Path, code string, severity Severity, parameters map[string]string, safeCause error, ) Violation
NewViolation constructs a violation. Parameters and paths are copied; malformed or unsafe diagnostic metadata fails closed.
func (Violation) Parameters ¶
Parameters returns a defensive copy of safe message parameters.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
adapters
|
|
|
config
Package validationconfig adapts typed validators to a small configuration validation contract.
|
Package validationconfig adapts typed validators to a small configuration validation contract. |
|
http
Package validationhttp provides router-neutral HTTP report projection.
|
Package validationhttp provides router-neutral HTTP report projection. |
|
jsonapi
Package validationjsonapi projects reports into JSON:API error objects.
|
Package validationjsonapi projects reports into JSON:API error objects. |
|
jsonrpc
Package validationjsonrpc projects reports into JSON-RPC invalid-params errors.
|
Package validationjsonrpc projects reports into JSON-RPC invalid-params errors. |
|
service
Package validationservice provides transport-neutral service hook contracts.
|
Package validationservice provides transport-neutral service hook contracts. |
|
Package rules provides reusable typed deterministic validators.
|
Package rules provides reusable typed deterministic validators. |
|
Package structplan provides optional typed and startup-compiled struct plans.
|
Package structplan provides optional typed and startup-compiled struct plans. |
|
Package validationconfig adapts typed validators to a small config contract.
|
Package validationconfig adapts typed validators to a small config contract. |
|
Package validationhttp provides router-neutral HTTP report projection.
|
Package validationhttp provides router-neutral HTTP report projection. |
|
Package validationjsonapi projects reports into JSON:API error objects.
|
Package validationjsonapi projects reports into JSON:API error objects. |
|
Package validationobserve exposes non-sensitive observation hooks.
|
Package validationobserve exposes non-sensitive observation hooks. |
|
Package validationrpc projects reports into JSON-RPC invalid-params errors.
|
Package validationrpc projects reports into JSON-RPC invalid-params errors. |
|
Package validationservice provides transport-neutral service hook contracts.
|
Package validationservice provides transport-neutral service hook contracts. |
|
Package validationtest provides reusable report assertions and conformance helpers for consumers.
|
Package validationtest provides reusable report assertions and conformance helpers for consumers. |
|
Package validationtext applies application-supplied message catalogs.
|
Package validationtext applies application-supplied message catalogs. |