Documentation
¶
Overview ¶
Package validator is a fast Go validator whose headline is a boolean rule DSL combining rules with &&, ||, !, () at precedence ! > && > || (e.g. `required && (in:admin,user || regex:"^g.+")`).
Data sources: struct tags, map, JSON, url.Values, Any, or a single Var.
required means present-and-non-nil: a zero value ("", 0, false) passes, a nil pointer or absent key fails. Use notblank/filled to reject empty strings, or WithStrictRequired to demand a non-zero value.
To negate a non-presence rule use its not_*/ne form, not !: omitempty makes in:a,b pass on "", so !in:a,b rejects "" while not_in:a,b passes it. ! is for presence rules like !required.
Example ¶
package main
import (
"context"
"fmt"
"github.com/libtnb/validator"
)
func main() {
type User struct {
Email string `validate:"required && email"`
Age int `validate:"required && gte:18"`
}
vd := validator.Struct(User{Email: "a@b.com", Age: 20})
vd.Validate(context.Background())
fmt.Println("valid:", !vd.Fails())
}
Output: valid: true
Index ¶
- func CheckRules(data any) error
- func IsEmpty(v any) bool
- func IsEmptyValue(rv reflect.Value) bool
- func SetDefault(v *Validator)
- func Valid(data any) bool
- type ErrorRule
- type Errors
- type Field
- type FieldError
- type FieldRules
- type Filter
- type Option
- func WithAttributes(attrs map[string]string) Option
- func WithMessages(messages map[string]string) Option
- func WithParallel(minFields int) Option
- func WithPrivateFieldValidation() Option
- func WithStrictRequired() Option
- func WithTagName(name string) Option
- func WithTagNameFunc(fn TagNameFunc) Option
- func WithTransformFunc(fn TransformFunc) Option
- func WithTranslation(messages map[string]string) Option
- func WithTranslator(fn TranslatorFunc) Option
- func WithoutBuiltinRules() Option
- type Rule
- type RuleInfo
- type TagNameFunc
- type TransformFunc
- type TranslatorFunc
- type Validation
- type Validator
- func (v *Validator) Any(data any) Validation
- func (v *Validator) CheckRules(data any) error
- func (v *Validator) DescribeRules(data any) ([]FieldRules, error)
- func (v *Validator) JSON(data string, rules map[string]string) Validation
- func (v *Validator) Map(data map[string]any, rules map[string]string) Validation
- func (v *Validator) RegisterErrorRule(rule ErrorRule)
- func (v *Validator) RegisterFilter(f Filter)
- func (v *Validator) RegisterFunc(signature string, fn func(Field) bool, message string)
- func (v *Validator) RegisterRule(rule Rule)
- func (v *Validator) RegisterStringFunc(signature string, fn func(value string, args ...string) bool, message string)
- func (v *Validator) Struct(data any) Validation
- func (v *Validator) URLValues(data url.Values, rules map[string]string) Validation
- func (v *Validator) Valid(data any) bool
- func (v *Validator) Var(value any, rule string) Validation
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func CheckRules ¶ added in v0.2.0
CheckRules reports every bad rule tag on data's struct type; see Validator.CheckRules.
func IsEmptyValue ¶
IsEmptyValue is the reflect.Value form of IsEmpty.
func SetDefault ¶ added in v0.3.0
func SetDefault(v *Validator)
SetDefault makes v the Validator returned by Default and used by the package-level helpers (Struct, Map, JSON, ...). Like slog.SetDefault it is meant to be called once during startup, before concurrent use — typically with an instance carrying custom rules, messages and translations, so the rest of the program can validate through the package funcs without passing a *Validator around.
Types ¶
type ErrorRule ¶
ErrorRule is a Rule variant returning an error; the engine prefers PassesE over Passes.
func ErrorRules ¶
func ErrorRules() []ErrorRule
type Errors ¶
type Errors interface {
// One returns the first message overall.
One() string
// OneFor returns the first message for field.
OneFor(field string) string
// Messages returns field's rule->message map.
Messages(field string) map[string]string
All() map[string]map[string]string
// Items returns every failure in evaluation order with resolved messages.
Items() []FieldError
Has(field string) bool
// String aggregates all messages (fields sorted), or "" when none failed.
String() string
}
Errors reads validation failures. Pure collection; deliberately not an error (use Validation.Err() for nil-on-success).
type Field ¶
type Field interface {
// Val is the current value; absent/nil is an invalid Value.
Val() reflect.Value
// Attrs are the parsed rule arguments (in:a,b,c -> [a b c]). The slice is
// shared with the compiled expression cache: read-only, never modify it.
Attrs() []string
// Name is the error-reporting name; for a dive element it is the bracketed
// key ("tags[0]") on the diagnostic path.
Name() string
// RootData is the whole data set, not this field's value.
RootData() any
Context() context.Context
// Sibling resolves another field (dotted name) relative-first then root-anchored, never itself.
Sibling(name string) (Field, bool)
}
Field is a value being validated, exposing sibling fields for cross-field rules. A Field is only valid for the duration of the rule call that receives it (the engine pools and reuses instances): never retain one.
type FieldError ¶
type FieldError struct {
Field string
Rule string
// Message is the raw template ({field}/{0}/...); root resolves it.
Message string
// Params are the rule arguments, resolving {0},{1},... placeholders.
Params []string
}
FieldError is the flat unit of a validation failure.
type FieldRules ¶ added in v0.4.0
type FieldRules struct {
// Name is the field's validation name, dotted for nested fields.
Name string
// Index locates the field for reflect.Type.FieldByIndex.
Index []int
// Rules apply to the field value itself.
Rules []RuleInfo
// Element rules apply to slice/array/map elements (dive).
Element []RuleInfo
// Exact is false when || or ! branches were omitted.
Exact bool
}
FieldRules lists the rules declared on one struct field, flattened from the top-level AND chain of its expression. Element holds the rules that apply to container elements (after dive). Rules under || or ! cannot be flattened losslessly: those subtrees are omitted and Exact reports false.
func DescribeRules ¶ added in v0.4.0
func DescribeRules(data any) ([]FieldRules, error)
DescribeRules calls Validator.DescribeRules on the package-level default.
type Option ¶
type Option func(*Validator)
Option configures a Validator during initialization.
func WithAttributes ¶
WithAttributes maps field names to display names for {field}.
func WithMessages ¶
WithMessages sets message templates keyed by "field.rule" (highest priority) or "rule".
func WithParallel ¶
WithParallel validates fields concurrently once a validation has at least minFields; values < 1 disable parallelism.
func WithPrivateFieldValidation ¶
func WithPrivateFieldValidation() Option
WithPrivateFieldValidation enables validation of unexported fields (via unsafe).
func WithStrictRequired ¶
func WithStrictRequired() Option
WithStrictRequired makes `required` reject zero values, not just absent/nil.
func WithTagName ¶
WithTagName sets the struct tag used for validation rules (default "validate").
func WithTagNameFunc ¶
func WithTagNameFunc(fn TagNameFunc) Option
WithTagNameFunc derives the tag name per field.
func WithTransformFunc ¶
func WithTransformFunc(fn TransformFunc) Option
WithTransformFunc sets a final transform over each resolved message.
func WithTranslation ¶
WithTranslation sets localized message templates keyed by "field.rule" or "rule".
func WithTranslator ¶
func WithTranslator(fn TranslatorFunc) Option
WithTranslator sets a function consulted after WithTranslation's map.
func WithoutBuiltinRules ¶
func WithoutBuiltinRules() Option
WithoutBuiltinRules disables registration of the built-in rules and filters.
type Rule ¶
Rule is a leaf boolean rule; composition (&&, ||, !) is handled by the DSL. Passes must be deterministic and side-effect free: the engine may evaluate a rule more than once for one value (fast probe + diagnostics on dive elements, exhaustive Errors() collection).
type RuleInfo ¶ added in v0.4.0
RuleInfo is one rule invocation in a field's expression, e.g. min:3.
type TagNameFunc ¶
type TagNameFunc func(field reflect.StructField) string
TagNameFunc derives a field's validation name from its StructField; an empty return keeps the Go field name.
type TransformFunc ¶
TransformFunc is a final transform applied to each resolved error message.
type TranslatorFunc ¶
TranslatorFunc returns a rule's template, or false to fall through.
type Validation ¶
type Validation interface {
// AddRules ANDs rule expressions onto a field's existing expression.
AddRules(field string, rules ...string) error
AddFilters(field string, filters ...string) error
RemoveRules(field string, rules ...string) error
RemoveFilters(field string, filters ...string) error
// ClearRules/ClearFilters drop a field's whole expression/chain.
ClearRules(field string) error
ClearFilters(field string) error
// AddMessages overrides message templates for this run only, outranking WithMessages.
AddMessages(messages map[string]string) error
Rules() map[string]string
Filters() map[string]string
// Bind writes the ORIGINAL data to ptr without requiring Validate.
Bind(ptr any) error
// SafeBind writes the FILTERED data to ptr; errors unless Validate passed.
SafeBind(ptr any) error
// Validate must run before accessing errors.
Validate(ctx context.Context)
// Errors is ALWAYS non-nil and not an error; never compare it to nil.
Errors() Errors
// Err is nil on success, else the failures.
Err() error
Fails() bool
}
Validation represents a single validation run over one data set. It is not safe for concurrent use; configure it (AddRules/AddFilters) before Validate — mutators after Validate have no effect on the already-computed result.
func Any ¶
func Any(data any) Validation
func Struct ¶
func Struct(data any) Validation
type Validator ¶
type Validator struct {
// contains filtered or unexported fields
}
Validator is a reusable, concurrency-safe factory for validations.
func Default ¶
func Default() *Validator
Default returns the shared Validator behind the package funcs; mutating it is process-global. It is created on first use unless SetDefault installed one earlier.
func NewValidator ¶
NewValidator creates a Validator, registering built-in rules unless WithoutBuiltinRules is given.
func (*Validator) Any ¶
func (v *Validator) Any(data any) Validation
Any validates a map, a struct (tags are read), or a scalar.
func (*Validator) CheckRules ¶ added in v0.2.0
CheckRules eagerly compiles every rule expression reachable from data's struct type (nested and embedded fields included) and reports all bad tags — unknown rules, DSL syntax errors, bad static args — as one joined error. Call it from a test or at startup to catch tag typos before request time.
func (*Validator) DescribeRules ¶ added in v0.4.0
func (v *Validator) DescribeRules(data any) ([]FieldRules, error)
DescribeRules reports the validation rules declared on data's struct type, for consumers that translate them into another representation — an OpenAPI generator mapping min:3 to minLength, for instance. Unknown rules are reported as-is rather than rejected; pair with CheckRules to catch typos.
func (*Validator) JSON ¶
func (v *Validator) JSON(data string, rules map[string]string) Validation
JSON decodes and validates a JSON object; a decode error or non-object top-level value is reported as a validation error.
func (*Validator) Map ¶
Map validates a map against the given field->rule expressions.
Example ¶
package main
import (
"context"
"fmt"
"github.com/libtnb/validator"
)
func main() {
v := validator.NewValidator()
vd := v.Map(
map[string]any{"name": "alice"},
// boolean DSL: AND-grouped OR
map[string]string{"name": "required && (alpha || in:bob,carol)"},
)
vd.Validate(context.Background())
fmt.Println("valid:", !vd.Fails())
}
Output: valid: true
func (*Validator) RegisterErrorRule ¶
func (*Validator) RegisterFilter ¶
func (*Validator) RegisterFunc ¶
RegisterFunc registers a rule from a plain function.
func (*Validator) RegisterRule ¶
RegisterRule registers a custom rule and invalidates caches so later validations pick it up; register before constructing the validations that use it. An unusable signature (blank, DSL syntax, reserved "dive") panics, like http.ServeMux.Handle.
func (*Validator) RegisterStringFunc ¶ added in v0.2.0
func (v *Validator) RegisterStringFunc(signature string, fn func(value string, args ...string) bool, message string)
RegisterStringFunc registers a string rule with the built-in conventions pre-applied: empty values pass (omitempty) and the value arrives rendered as a string, so fn only holds the actual check.
func (*Validator) Struct ¶
func (v *Validator) Struct(data any) Validation
Struct validates a struct using its tags plus any added rules.
Source Files
¶
- cache.go
- collection.go
- comparison.go
- compile.go
- crossfield.go
- data.go
- defaults.go
- doc.go
- errors.go
- eval.go
- field.go
- file.go
- filter.go
- filters.go
- format.go
- helpers.go
- introspect.go
- message.go
- numeric.go
- option.go
- presence.go
- reflect.go
- registry.go
- ruleexpr.go
- rules.go
- scope.go
- source.go
- string.go
- struct.go
- time.go
- types.go
- validation.go
- validator.go
Directories
¶
| Path | Synopsis |
|---|---|
|
Command examples is a runnable validator demo; the leading-underscore dir is skipped by the go tool, so run it directly: go run ./_examples
|
Command examples is a runnable validator demo; the leading-underscore dir is skipped by the go tool, so run it directly: go run ./_examples |
|
contrib
|
|
|
gormrules
module
|
|
|
openapi
module
|
|
|
Package conv provides fast type conversions.
|
Package conv provides fast type conversions. |
|
internal
|
|
|
dsl
Package dsl is the boolean rule-expression engine: lexer, parser (! > && > ||), AST, dive splitting.
|
Package dsl is the boolean rule-expression engine: lexer, parser (! > && > ||), AST, dive splitting. |
|
Package is provides pure predicates for common string formats.
|
Package is provides pure predicates for common string formats. |