Documentation
¶
Overview ¶
Package validation provides struct and variable validation using struct tags.
Use this package to validate Go values against constraints defined in struct field tags. The package supports validating entire structs with the Struct function or individual variables with the Var function.
Validation rules are specified using the "validate" struct tag. Multiple rules can be combined with commas. For example:
type User struct {
Name string `validate:"required,min=1,max=100"`
Age int `validate:"required,gte=0,lte=150"`
Email string `validate:"required"`
}
Built-in validators include required, omitempty, gt, gte, lt, lte, len, min, max, oneof, dive, ip_addr, absolute_path, filepath, and required_if. Custom validators can be registered to extend the validation capabilities. Aliases can also be registered to create reusable combinations of validators.
Validation errors are returned as joined errors containing field-specific information including the field name, validator name, and the reason for failure.
Index ¶
- Constants
- func MustRegisterAlias(name string, expansion string)
- func MustRegisterValidator(name Validator, callback Callback)
- func Struct(val any) error
- func Var[T any](val T, validatorInstructions string) error
- type Callback
- type CallbackParameters
- type CallbackResult
- type FieldError
- type Validator
Constants ¶
const ( // ValidatorsSep is the separator between validation names. For example: "required,oneof=THIS THAT". ValidatorsSep = "," // NameAndInstructionsSep is the separator between the validation name and the instructions. // For example: "oneof=THIS THAT". NameAndInstructionsSep = "=" // Tag is the name of the struct field tag. // // type Example struct { // Value *int `validate:"required,gt=0"` // } // // The tag contains the validators and their respective instructions. Tag = "validate" )
Variables ¶
This section is empty.
Functions ¶
func MustRegisterAlias ¶
MustRegisterAlias sets the expansion for an alias.
func MustRegisterValidator ¶
MustRegisterValidator registers a validator callback and panics on duplicates.
Types ¶
type Callback ¶
type Callback func(*CallbackParameters) (*CallbackResult, error)
Callback executes a validator and returns how validation should proceed.
type CallbackParameters ¶
type CallbackParameters struct {
// Validator is the name of the validator being executed.
Validator Validator
// IsStructValidation reports whether validation is running against a struct field.
IsStructValidation bool
// StructValue holds the parent struct when validating a struct field.
StructValue reflect.Value
// StructFieldName names the struct field being validated.
StructFieldName string
// Value is the value currently being validated.
Value reflect.Value
// Parameters carries the validator instruction string after the name.
Parameters string
}
CallbackParameters holds context for a validator callback, including struct data when available.
type CallbackResult ¶
type CallbackResult struct {
// contains filtered or unexported fields
}
CallbackResult carries a validator outcome and directs validation flow.
func NewCallbackResult ¶
func NewCallbackResult() *CallbackResult
NewCallbackResult provides a blank result for validators to populate.
func (*CallbackResult) AddFieldError ¶
func (c *CallbackResult) AddFieldError(fieldError *FieldError) *CallbackResult
AddFieldError appends a field error to the result.
func (*CallbackResult) AddValue ¶
func (c *CallbackResult) AddValue(val reflect.Value) *CallbackResult
AddValue queues additional values for the remaining validators in the tag. For example, dive adds each element so later validators apply to them.
func (*CallbackResult) PassValidation ¶
func (c *CallbackResult) PassValidation() *CallbackResult
PassValidation signals that validation passed and should continue to the next validator.
func (*CallbackResult) StopValidation ¶
func (c *CallbackResult) StopValidation() *CallbackResult
StopValidation signals that remaining validators should be skipped for the field.
type FieldError ¶
type FieldError struct {
// contains filtered or unexported fields
}
FieldError represents a failure for a specific validator.
func NewFieldError ¶
func NewFieldError(params *CallbackParameters, err error) *FieldError
NewFieldError instantiates a *FieldError.
func (*FieldError) Error ¶
func (v *FieldError) Error() string
Error ensures FieldError has the error interface.
func (*FieldError) Unwrap ¶
func (v *FieldError) Unwrap() error
Unwrap returns the underlying wrapped error.
type Validator ¶
type Validator string
Validator is the name of a validate rule. For example: oneof, required, dive, etc...
const ( // GreaterThanValidatorName is the name of the validator that checks // if a numeric value is greater than a threshold. GreaterThanValidatorName Validator = "gt" // GreaterThanOrEqualValidatorName is the name of the validator that checks // if a numeric value is greater than or equal to a threshold. GreaterThanOrEqualValidatorName Validator = "gte" // LessThanValidatorName is the name of the validator that checks // if a numeric value is less than a threshold. LessThanValidatorName Validator = "lt" // LessThanOrEqualValidatorName is the name of the validator that checks // if a numeric value is less than or equal to a threshold. LessThanOrEqualValidatorName Validator = "lte" )
const ( // LenValidatorName is the name of the validator that checks if a string has an exact byte length. LenValidatorName Validator = "len" // MinValidatorName is the name of the validator that checks if a string has a minimum byte length. MinValidatorName Validator = "min" // MaxValidatorName is the name of the validator that checks if a string has a maximum byte length. MaxValidatorName Validator = "max" )
const ( // AbsolutePathValidatorName is the name of the validator that enforces absolute, valid, existing filesystem paths. AbsolutePathValidatorName Validator = "absolute_path" )
const ( // DiveValidatorName is the name of the validator that iterates over slice elements for validation. DiveValidatorName Validator = "dive" )
const ( // FilepathValidatorName is the name of the validator that checks if a file path is accessible. FilepathValidatorName Validator = "filepath" )
const ( // IPAddrValidatorName is the name of the validator that checks if a string is a valid IP address. IPAddrValidatorName Validator = "ip_addr" )
const ( // OmitemptyValidatorName is the name of the validator that skips subsequent validators if the value is empty. OmitemptyValidatorName Validator = "omitempty" )
const ( // OneOfValidatorName is the name of the validator that checks if a value matches one of the allowed values. OneOfValidatorName Validator = "oneof" )
const ( // RequiredIfValidatorName is the name of the validator that // conditionally requires a field based on another field's value. RequiredIfValidatorName Validator = "required_if" )
const ( // RequiredValidatorName is the name of the validator that checks if a value is non-nil and non-zero. RequiredValidatorName Validator = "required" )