Documentation
¶
Overview ¶
Package valid provides struct validation backed by github.com/go-playground/validator/v10.
Create a validator with New:
v := valid.New()
Validate a struct:
type CreateUserRequest struct {
Name string `validate:"required"`
Email string `validate:"required,email"`
Age int `validate:"min=18,max=120"`
}
err := v.Struct(req)
if err != nil {
// err is a *xerrors.Err with code ErrInvalidInput.
// Use errors.As to inspect it.
}
Use Spanish messages:
v := valid.New(valid.WithMessageProvider(valid.SpanishMessages))
Use a custom message provider:
type myMessages struct{}
func (m myMessages) Message(field, tag, param string) string { ... }
v := valid.New(valid.WithMessageProvider(myMessages{}))
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type MessageProvider ¶
MessageProvider maps a validation failure to a human-readable message.
- field: the struct field name (e.g. "Email")
- tag: the failing validation rule (e.g. "required", "email", "min")
- param: the rule parameter if any (e.g. "18" for min=18), or "" if none
var DefaultMessages MessageProvider = defaultMessages{}
DefaultMessages is the built-in English message provider. Used automatically when no WithMessageProvider option is given.
var SpanishMessages MessageProvider = spanishMessages{}
SpanishMessages is an opt-in Spanish message provider.
type Option ¶
type Option func(*config)
Option configures a Validator.
func WithMessageProvider ¶
func WithMessageProvider(mp MessageProvider) Option
WithMessageProvider sets a custom MessageProvider. Default: DefaultMessages (English).
type Validator ¶
type Validator interface {
// Struct validates v and returns a *xerrors.Err if validation fails.
// Returns nil if v is valid.
// Returns ErrInvalidInput for field constraint failures (first error only).
// Returns ErrInternal if v is not a struct.
Struct(v any) error
}
Validator validates structs using struct tags.
Click to show internal directories.
Click to hide internal directories.