Documentation
¶
Overview ¶
Package validator provides a wrapper around go-playground/validator with built-in translation support for validation error messages. It simplifies struct validation and error handling by providing formatted, human-readable error messages in English.
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ErrValidation = errors.New("validation error")
ErrValidation is a sentinel error value used to identify validation errors.
Functions ¶
Types ¶
type FieldLevel ¶
type FieldLevel = validator.FieldLevel
FieldLevel is a type alias for validator.FieldLevel.
type Validator ¶
type Validator struct {
// contains filtered or unexported fields
}
Validator wraps the go-playground/validator functionality with translation support. It holds both the validator instance and a translator for converting validation errors into human-readable messages.
func New ¶
func New() *Validator
New creates and initializes a new Validator instance with English translations. It sets up the universal translator with English locale and registers the default English translations for validation error messages.
func (*Validator) FormatErrors ¶
FormatErrors converts validator.ValidationErrors into a slice of standard errors. It translates the validation errors into human-readable messages using the configured translator. Returns nil if there are no errors to format.
func (*Validator) RegisterValidationAndTranslation ¶
func (v *Validator) RegisterValidationAndTranslation(tag string, fn validator.Func, msgTemplate string) error
RegisterValidationAndTranslation registers both a validation function and its error message translation.
It simplifies the process of adding custom validations with proper error messages. Parameters:
- tag: the validation tag to use in struct field tags
- fn: the validation function that implements the validation logic
- msgTemplate: the error message template (use {0} for the field name and {1} for the parameter)
Example usage:
validator.RegisterValidationAndTranslation(
"multiple",
validateMultiple,
"{0} must be a multiple of {1}"
)
where `validateMultiple` is for example:
func validateMultiple(fl validator.FieldLevel) bool {
value := fl.Field().Int()
// Get the parameter from the tag (the number after 'multiple=')
param := fl.Param()
multiplier, err := strconv.Atoi(param)
if err != nil {
return false // Invalid parameter
}
// Check if value is a multiple of the specified number
return value%int64(multiplier) == 0
}