Documentation
¶
Overview ¶
Package validate provides struct-tag-driven data validation with built-in rules, custom rule registration, nested struct validation, and slice validation.
Quick Start ¶
type User struct {
Name string `validate:"required,min=3,max=50"`
Email string `validate:"required,email"`
Age int `validate:"min=18,max=120"`
Password string `validate:"required,min=8"`
Confirm string `validate:"eqfield=Password"`
}
user := User{Name: "ab", Email: "invalid", Age: 5}
err := validate.Validate(user)
// → returns *validate.Errors with field-specific messages
Built-in Rules ¶
required — field must not be zero value min=N — minimum value (numbers) or length (strings/slices) max=N — maximum value (numbers) or length (strings/slices) len=N — exact length (strings/slices) or value (numbers) eq=N — must equal N ne=N — must not equal N gt=N — greater than N gte=N — greater than or equal to N lt=N — less than N lte=N — less than or equal to N oneof=a b c — must be one of the listed values email — must be a valid email address url — must be a valid URL ip — must be a valid IP address ipv4 — must be a valid IPv4 address ipv6 — must be a valid IPv6 address alpha — must contain only alpha characters alphanum — must contain only alphanumeric characters numeric — must contain only numeric characters contains=s — must contain substring s startswith=s — must start with s endswith=s — must end with s regex=pattern — must match the regex pattern eqfield=Name — must equal another field's value nefield=Name — must not equal another field's value gtfield=Name — must be greater than another field's value ltefield=Name — must be less than or equal to another field's value unique — slice elements must be unique dive — validate slice/map elements recursively nostructlevel — skip nested struct validation (opt-in)
Custom Rules ¶
validate.AddRule("phone", func(value any, param string, parent any) error {
s, ok := value.(string)
if !ok { return validate.ErrInvalidType }
if !phoneRegex.MatchString(s) {
return fmt.Errorf("invalid phone number")
}
return nil
})
type Contact struct {
Phone string `validate:"required,phone"`
}
Nested Validation ¶
Nested structs are validated automatically. Use the `dive` rule to validate elements of a slice or values of a map.
type Order struct {
Items []Item `validate:"required,dive"`
}
Index ¶
- Variables
- func AddRule(name string, fn RuleFunc)
- func HasRule(name string) bool
- func RegisteredRules() []string
- func ResetRules()
- func Validate(v any) error
- func ValidateEmail(s string) bool
- func ValidateMap(m any, tag string) map[any]error
- func ValidateSlice(slice any, tag string) map[int]error
- func ValidateWithTag(value any, tag string) error
- type Errors
- type FieldError
- type RuleFunc
Constants ¶
This section is empty.
Variables ¶
var ( // ErrInvalidType is returned by a rule when the field value is not // of the expected type. ErrInvalidType = errors.New("validate: invalid field type for rule") // ErrNoValidator is returned when a custom rule is not found. ErrNoValidator = errors.New("validate: no validator registered for rule") )
Sentinel errors.
Functions ¶
func AddRule ¶
AddRule registers a custom validation rule. The rule name must be lowercase and not conflict with built-in rules (it will overwrite built-in rules if it does).
func RegisteredRules ¶
func RegisteredRules() []string
RegisteredRules returns the names of all registered rules (built-in + custom).
func ResetRules ¶
func ResetRules()
ResetRules restores the default built-in rule set, removing any custom rules added via AddRule. This is primarily useful for testing.
func Validate ¶
Validate validates a struct and returns all field errors. Returns nil if the value is valid. Non-struct values are validated against any rules found in the default tag (not typical — use ValidateWithTag for inline validation).
func ValidateEmail ¶ added in v0.1.1
ValidateEmail reports whether s is a valid email address. It uses the same logic as the "email" validation rule (net/mail.ParseAddress).
func ValidateMap ¶
ValidateMap validates each value in a map against the given tag. Returns a map of key → error for all invalid values. Returns nil if all values are valid.
func ValidateSlice ¶
ValidateSlice validates each element of a slice against the given tag. Returns a map of index → error for all invalid elements. Returns nil if all elements are valid.
This is a convenience function for validating slices outside of a struct context:
errs := validate.ValidateSlice([]string{"a", "ab", "abc"}, "min=2")
// errs[0] = error for "a" (length < 2)
func ValidateWithTag ¶
ValidateWithTag validates a single value against a tag string (e.g. "required,min=3"). This is useful for validating individual values outside of a struct context.
Types ¶
type Errors ¶
type Errors []FieldError
Errors is a collection of field errors.
type FieldError ¶
type FieldError struct {
Field string // dotted path, e.g. "User.Address.Street"
Rule string // rule that failed, e.g. "required", "min"
Value any // the invalid value
Message string // human-readable error message
}
FieldError describes a validation failure for a single field.
func (FieldError) Error ¶
func (e FieldError) Error() string