Documentation
¶
Overview ¶
Package validator provides struct tag-based validation with no external dependencies.
Built-in Validators ¶
Core validators:
required - Field must not be empty/zero value omitempty - Skip validation if field is empty eq - Equal to value ne - Not equal to value
String validators:
min - Minimum length (runes) max - Maximum length (runes) len - Exact length contains - Contains substring startswith - Starts with prefix endswith - Ends with suffix excludes - Excludes substring alpha - Letters only (Unicode) alphanum - Letters and numbers only lowercase - All lowercase uppercase - All uppercase ascii - ASCII characters only printascii - Printable ASCII only numeric - Numeric digits only oneof - One of allowed values (space-separated)
Numeric validators:
min - Minimum value max - Maximum value gt - Greater than lt - Less than gte - Greater than or equal lte - Less than or equal
Format validators:
email - Email address format uuid - UUID format datetime - Custom datetime format base64 - Base64 encoded hexadecimal - Hex string hexcolor - Hex color (#RGB, #RGBA, #RRGGBB, #RRGGBBAA) e164 - E.164 phone number semver - Semantic version jwt - JWT format (3 base64 parts) boolean - Boolean string (true/false/yes/no/on/off/1/0) json - Valid JSON
Network validators:
ip - IP address (v4 or v6) ipv4 - IPv4 address ipv6 - IPv6 address cidr - CIDR notation hostname - RFC 952 hostname uri - Absolute URI url - HTTP/HTTPS URL
Collection validators:
unique - Unique elements in slice each - Validate each element anyof - At least one element matches (space-separated, for slices/arrays)
Usage ¶
type User struct {
Name string `validate:"required,min=2,max=50"`
Email string `validate:"required,email"`
Age int `validate:"min=13,max=120"`
}
if err := validator.Struct(&user); err != nil {
// Handle ValidationErrors
}
Index ¶
Constants ¶
This section is empty.
Variables ¶
var Registry = &typeRegistry{}
Registry is the package-level type registry instance.
Functions ¶
func IsBindError ¶
IsBindError checks if an error is a binding error.
func IsUnknownFieldError ¶ added in v0.90.0
IsUnknownFieldError checks if an error is an unknown field error.
Types ¶
type BindError ¶
type BindError struct {
Err error
}
BindError wraps binding errors to distinguish them from validation errors. The default error handler uses this to return 400 instead of 422.
type UnknownFieldError ¶ added in v0.90.0
type UnknownFieldError struct {
Field string
}
UnknownFieldError indicates a JSON payload contained a field not present in the target struct. The default error handler uses this to return 422 Unprocessable Entity instead of 400 Bad Request.
func (*UnknownFieldError) Error ¶ added in v0.90.0
func (e *UnknownFieldError) Error() string
type ValidationErrorer ¶
ValidationErrorer is implemented by validation error types. The default error handler uses this to detect validation errors and return 422 Unprocessable Entity with proper formatting.
type ValidationErrors ¶
ValidationErrors holds all validation errors for a struct. The key is the field path (e.g., "Name", "Address.City", "Items[0].Name").
func (ValidationErrors) Add ¶
func (ve ValidationErrors) Add(field, err string)
Add adds an error for a specific field.
func (ValidationErrors) Error ¶
func (ve ValidationErrors) Error() string
Error implements the error interface.
func (ValidationErrors) FieldErrors ¶
func (ve ValidationErrors) FieldErrors(field string) []string
FieldErrors returns all errors for a specific field.
func (ValidationErrors) HasErrors ¶
func (ve ValidationErrors) HasErrors() bool
HasErrors returns true if there are any validation errors.
func (ValidationErrors) ValidationErrors ¶
func (ve ValidationErrors) ValidationErrors() map[string][]string
ValidationErrors returns the errors map (implements ValidationErrorer interface).
type ValidationFunc ¶
ValidationFunc is a custom validation function. It receives the field value and returns an error if validation fails.
type Validator ¶
type Validator interface {
// Struct validates a struct using `validate` struct tags.
// It returns a ValidationErrors containing all validation failures,
// or nil if the struct is valid.
Struct(dst any) error
// Register adds a custom validation function with the given name.
// The name can be used in struct tags like `validate:"customName"`.
Register(name string, fn ValidationFunc)
}
Validator handles struct validation using reflection and struct tags.