Documentation ¶
Overview ¶
Package vax validation provides configurable and extensible rules for validating data of various types.
Index ¶
- Variables
- func Combine(params ...any) string
- func EnsureString(value interface{}) (string, error)
- func Indirect(value interface{}) (interface{}, bool)
- func IsEmpty(value interface{}) bool
- func Len(val any, rune bool) (int, error)
- func LengthOfValue(value interface{}) (int, error)
- func SetTranslator(t Translator)
- func StringOrBytes(value interface{}) (isString bool, str string, isBytes bool, bs []byte)
- func Struct(structPtr interface{}, lang string, fields ...*FieldRules) error
- func StructWithCtx(ctx context.Context, lang string, structPtr interface{}, fields ...*FieldRules) error
- func ToFloat(value interface{}) (float64, error)
- func ToInt(value interface{}) (int64, error)
- func ToUint(value interface{}) (uint64, error)
- func Validate(lang string, value interface{}, rules ...Rule) error
- func ValidateWithContext(ctx context.Context, lang string, value interface{}, rules ...Rule) error
- type CompareRule
- type EachRule
- type EqLengthRule
- type Err
- type ErrFieldNotFound
- type ErrFieldPointer
- type Error
- type ErrorObject
- func (e ErrorObject) AddParams(args ...any) Error
- func (e ErrorObject) Code() string
- func (e ErrorObject) Error() string
- func (e ErrorObject) Lang() string
- func (e ErrorObject) Message() string
- func (e ErrorObject) Params() []any
- func (e ErrorObject) SetCode(code string) Error
- func (e ErrorObject) SetLang(s string) Error
- func (e ErrorObject) SetMessage(message string) Error
- type Errors
- type FieldRules
- type InRule
- type InternalError
- type KeyRules
- type MapRule
- type MatchRule
- type MaxLengthRule
- type MinLengthRule
- type MultipleOfRule
- type NotInRule
- type RangeLengthRule
- type RequiredRule
- type Rule
- type RuleFunc
- type RuleWithContext
- type RuleWithContextFunc
- type StringRule
- type Translator
- type Validatable
- type ValidatableWithContext
- type WhenRule
Constants ¶
This section is empty.
Variables ¶
var ( // ErrNil is the error that returns when a value is not nil. ErrNil = NewError("validate.isnil", "must be blank") // ErrEmpty is the error that returns when a not nil value is not empty. ErrEmpty = NewError("validate.isempty", "must be blank") )
var ( // ErrLengthTooLong is the error that returns in case of too long length. ErrLengthTooLong = NewError("validate.length.max", "the length must be no more than %v") // ErrLengthTooShort is the error that returns in case of too short length. ErrLengthTooShort = NewError("validate.length.min", "the length must be no less than %v") // ErrLengthInvalid is the error that returns in case of an invalid length. ErrLengthInvalid = NewError("validate.length.eq", "the length must be exactly %v") // ErrLengthOutOfRange is the error that returns in case of out of range length. ErrLengthOutOfRange = NewError("validate.length.range", "the length must be between %v and %v") )
var ( // ErrNotMap is the error that the value being validated is not a map. ErrNotMap = errors.New("only a map can be validated") // ErrKeyWrongType is the error returned in case of an incorrect key type. ErrKeyWrongType = NewError("validation_key_wrong_type", "key not the correct type") // ErrKeyMissing is the error returned in case of a missing key. ErrKeyMissing = NewError("validation_key_missing", "required key is missing") // ErrKeyUnexpected is the error returned in case of an unexpected key. ErrKeyUnexpected = NewError("validation_key_unexpected", "key not expected") )
var ( // ErrMinGreaterEqualThanRequired is the error that returns when a value is less than a specified threshold. ErrMinGreaterEqualThanRequired = NewError("validate.gte", "must be greater than or equal to %v") // ErrMaxLessEqualThanRequired is the error that returns when a value is greater than a specified threshold. ErrMaxLessEqualThanRequired = NewError("validate.lte", "must be less than or equal to %v") // ErrMinGreaterThanRequired is the error that returns when a value is less than or equal to a specified threshold. ErrMinGreaterThanRequired = NewError("validate.gt", "must be greater than %v") // ErrMaxLessThanRequired is the error that returns when a value is greater than or equal to a specified threshold. ErrMaxLessThanRequired = NewError("validate.lt", "must be less than %v") ErrEqualRequired = NewError("validate.eq", "must be equal to %v") )
var ( // ErrRequired is the error that returns when a value is required. ErrRequired = NewError("validate.required", "is required") // ErrNilOrNotEmpty is the error that returns when a value is not nil and is empty. ErrNilOrNotEmpty = NewError("validate.empty", "cannot be blank") )
var ( // LabelTag is the struct tag name used to customize the error field name for a struct field. LabelTag = "label" // Skip is a special validation rule that indicates all rules following it should be skipped. Skip = skipRule{/* contains filtered or unexported fields */} )
var Empty = absentRule{/* contains filtered or unexported fields */}
Empty checks if a not nil value is empty.
var ErrInInvalid = NewError("validate.oneof", "must be oneof value in [%v]")
ErrInInvalid is the error that returns in case of an invalid value for "in" rule.
var ErrMatchInvalid = NewError("validate.match", "must match regular expression %v")
ErrMatchInvalid is the error that returns in case of invalid format.
var ErrMultipleOfInvalid = NewError("validate.multiple", "must be multiple of %v")
ErrMultipleOfInvalid is the error that returns when a value is not multiple of a base.
var ErrNotInInvalid = NewError("validate.notoneof", "cannot be one of several values [%v]")
ErrNotInInvalid is the error that returns when a value is in a list.
var ErrNotNilRequired = NewError("validate.notnil", "can not be nil")
ErrNotNilRequired is the error that returns when a value is Nil.
var ( // ErrStructPointer is the error that a struct being validated is not specified as a pointer. ErrStructPointer = errors.New("only a pointer to a struct can be validated") )
var Nil = absentRule{/* contains filtered or unexported fields */}
Nil is a validation rule that checks if a value is nil. It is the opposite of NotNil rule
var NilOrNotEmpty = RequiredRule{/* contains filtered or unexported fields */}
NilOrNotEmpty checks if a value is a nil pointer or a value that is not empty. NilOrNotEmpty differs from Required in that it treats a nil pointer as valid.
var NotNil = notNilRule{}
NotNil is a validation rule that checks if a value is not nil. NotNil only handles types including interface, pointer, slice, and map. All other types are considered valid.
var Required = RequiredRule{/* contains filtered or unexported fields */}
Required is a validation rule that checks if a value is not empty. A value is considered not empty if - integer, float: not zero - bool: true - string, array, slice, map: len() > 0 - interface, pointer: not nil and the referenced value is not empty - any other types
Functions ¶
func EnsureString ¶
EnsureString ensures the given value is a string. If the value is a byte slice, it will be typecast into a string. An error is returned otherwise.
func Indirect ¶
func Indirect(value interface{}) (interface{}, bool)
Indirect returns the value that the given interface or pointer references to. If the value implements driver.Valuer, it will deal with the value returned by the Value() method instead. A boolean value is also returned to indicate if the value is nil or not (only applicable to interface, pointer, map, and slice). If the value is neither an interface nor a pointer, it will be returned back.
func IsEmpty ¶
func IsEmpty(value interface{}) bool
IsEmpty checks if a value is empty or not. A value is considered empty if - integer, float: zero - bool: false - string, array: len() == 0 - slice, map: nil or len() == 0 - interface, pointer: nil or the referenced value is empty
func LengthOfValue ¶
LengthOfValue returns the length of a value that is a string, slice, map, or array. An error is returned for all other types.
func SetTranslator ¶
func SetTranslator(t Translator)
func StringOrBytes ¶
StringOrBytes typecasts a value into a string or byte slice. Boolean flags are returned to indicate if the typecasting succeeds or not.
func Struct ¶
func Struct(structPtr interface{}, lang string, fields ...*FieldRules) error
Struct validates a struct by checking the specified struct fields against the corresponding validation rules. Note that the struct being validated must be specified as a pointer to it. If the pointer is nil, it is considered valid. Use Field() to specify struct fields that need to be validated. Each Field() call specifies a single field which should be specified as a pointer to the field. A field can be associated with multiple rules. For example,
value := struct { Username string Value string }{"name", "demo"} err := validation.Struct(&value, validation.Field(&a.Username, validation.Required), validation.Field(&a.Value, validation.Required, validation.RangeLength(5, 10)), ) fmt.Println(err) // Value: the length must be between 5 and 10.
An error will be returned if validation fails.
func StructWithCtx ¶
func StructWithCtx(ctx context.Context, lang string, structPtr interface{}, fields ...*FieldRules) error
StructWithCtx validates a struct with the given context. The only difference between StructWithCtx and Struct is that the former will validate struct fields with the provided context. Please refer to Struct for the detailed instructions on how to use this function.
func ToFloat ¶
ToFloat converts the given value to a float64. An error is returned for all incompatible types.
func ToInt ¶
ToInt converts the given value to an int64. An error is returned for all incompatible types.
func ToUint ¶
ToUint converts the given value to an uint64. An error is returned for all incompatible types.
func Validate ¶
Validate validates the given value and returns the validation error, if any.
Validate performs validation using the following steps:
- For each rule, call its `Validate()` to validate the value. Return if any error is found.
- If the value being validated implements `Validatable`, call the value's `Validate()`. Return with the validation result.
- If the value being validated is a map/slice/array, and the element type implements `Validatable`, for each element call the element value's `Validate()`. Return with the validation result.
func ValidateWithContext ¶
ValidateWithContext validates the given value with the given context and returns the validation error, if any.
ValidateWithContext performs validation using the following steps:
- For each rule, call its `ValidateWithContext()` to validate the value if the rule implements `RuleWithContext`. Otherwise call `Validate()` of the rule. Return if any error is found.
- If the value being validated implements `ValidatableWithContext`, call the value's `ValidateWithContext()` and return with the validation result.
- If the value being validated implements `Validatable`, call the value's `Validate()` and return with the validation result.
- If the value being validated is a map/slice/array, and the element type implements `ValidatableWithContext`, for each element call the element value's `ValidateWithContext()`. Return with the validation result.
- If the value being validated is a map/slice/array, and the element type implements `Validatable`, for each element call the element value's `Validate()`. Return with the validation result.
Types ¶
type CompareRule ¶
type CompareRule struct {
// contains filtered or unexported fields
}
CompareRule is a validation rule that checks if a value satisfies the specified threshold requirement.
func Eq ¶
func Eq(num any) CompareRule
func Gt ¶
func Gt(min interface{}) CompareRule
func Gte ¶
func Gte(min interface{}) CompareRule
func Lt ¶
func Lt(max interface{}) CompareRule
func Lte ¶
func Lte(max interface{}) CompareRule
func (CompareRule) Code ¶
func (r CompareRule) Code(code string) Rule
func (CompareRule) Msg ¶
func (r CompareRule) Msg(msg string) Rule
func (CompareRule) Validate ¶
func (r CompareRule) Validate(lang string, value interface{}) error
Validate checks if the given value is valid or not.
type EachRule ¶
type EachRule struct {
// contains filtered or unexported fields
}
EachRule is a validation rule that validates elements in a map/slice/array using the specified list of rules.
func Each ¶
Each returns a validation rule that loops through an iterable (map, slice or array) and validates each value inside with the provided rules. An empty iterable is considered valid. Use the Required rule to make sure the iterable is not empty.
type EqLengthRule ¶
type EqLengthRule struct {
// contains filtered or unexported fields
}
func EqLength ¶
func EqLength(l int, rune bool) EqLengthRule
func (EqLengthRule) Code ¶
func (r EqLengthRule) Code(code string) Rule
func (EqLengthRule) Msg ¶
func (r EqLengthRule) Msg(msg string) Rule
func (EqLengthRule) Validate ¶
func (r EqLengthRule) Validate(lang string, value interface{}) error
type ErrFieldNotFound ¶
type ErrFieldNotFound int
ErrFieldNotFound is the error that a field cannot be found in the struct.
func (ErrFieldNotFound) Error ¶
func (e ErrFieldNotFound) Error() string
Error returns the error string of ErrFieldNotFound.
type ErrFieldPointer ¶
type ErrFieldPointer int
ErrFieldPointer is the error that a field is not specified as a pointer.
func (ErrFieldPointer) Error ¶
func (e ErrFieldPointer) Error() string
Error returns the error string of ErrFieldPointer.
type Error ¶
type Error interface { Error() string SetLang(string) Error Lang() string SetCode(string) Error Code() string Message() string SetMessage(string) Error Params() []any AddParams(args ...any) Error }
Error interface represents an validation error
type ErrorObject ¶
type ErrorObject struct {
// contains filtered or unexported fields
}
ErrorObject is the default validation error that implements the Error interface.
func (ErrorObject) AddParams ¶
func (e ErrorObject) AddParams(args ...any) Error
AddParams set the error's params.
func (ErrorObject) Lang ¶
func (e ErrorObject) Lang() string
func (ErrorObject) Message ¶
func (e ErrorObject) Message() string
Message return the error's message.
func (ErrorObject) SetCode ¶
func (e ErrorObject) SetCode(code string) Error
SetCode set the error's translation code.
func (ErrorObject) SetLang ¶
func (e ErrorObject) SetLang(s string) Error
func (ErrorObject) SetMessage ¶
func (e ErrorObject) SetMessage(message string) Error
SetMessage set the error's message.
type Errors ¶
type Errors []Err
Errors represents the validation errors that are indexed by struct field names, map or slice keys. values are Error or Errors (for map, slice and array error value is Errors).
func (Errors) MarshalJSON ¶
MarshalJSON converts the Errors into a valid JSON.
type FieldRules ¶
type FieldRules struct {
// contains filtered or unexported fields
}
FieldRules represents a rule set associated with a struct field.
func Field ¶
func Field(fieldPtr interface{}, rules ...Rule) *FieldRules
Field specifies a struct field and the corresponding validation rules. The struct field must be specified as a pointer to it.
type InRule ¶
type InRule struct {
// contains filtered or unexported fields
}
InRule is a validation rule that validates if a value can be found in the given list of values.
func In ¶
func In(values ...interface{}) InRule
In returns a validation rule that checks if a value can be found in the given list of values. reflect.DeepEqual() will be used to determine if two values are equal. For more details please refer to https://golang.org/pkg/reflect/#DeepEqual An empty value is considered valid. Use the Required rule to make sure a value is not empty.
type InternalError ¶
InternalError represents an error that should NOT be treated as a validation error.
func NewInternalError ¶
func NewInternalError(err error) InternalError
NewInternalError wraps a given error into an InternalError.
type KeyRules ¶
type KeyRules struct {
// contains filtered or unexported fields
}
KeyRules represents a rule set associated with a map key.
type MapRule ¶
type MapRule struct {
// contains filtered or unexported fields
}
MapRule represents a rule set associated with a map.
func Map ¶
Map returns a validation rule that checks the keys and values of a map. This rule should only be used for validating maps, or a validation error will be reported. Use Key() to specify map keys that need to be validated. Each Key() call specifies a single key which can be associated with multiple rules. For example,
validation.Map( validation.Key("Username", validation.Required), validation.Key("Value", validation.Required, validation.RangeLength(5, 10)), )
A nil value is considered valid. Use the Required rule to make sure a map value is present.
func (MapRule) AllowExtraKeys ¶
AllowExtraKeys configures the rule to ignore extra keys.
type MatchRule ¶
type MatchRule struct {
// contains filtered or unexported fields
}
MatchRule is a validation rule that checks if a value matches the specified regular expression.
func Match ¶
Match returns a validation rule that checks if a value matches the specified regular expression. This rule should only be used for validating strings and byte slices, or a validation error will be reported. An empty value is considered valid. Use the Required rule to make sure a value is not empty.
type MaxLengthRule ¶
type MaxLengthRule struct {
// contains filtered or unexported fields
}
func MaxLenRune ¶
func MaxLenRune(max int) MaxLengthRule
func MaxLength ¶
func MaxLength(max int, rune bool) MaxLengthRule
func (MaxLengthRule) Code ¶
func (r MaxLengthRule) Code(code string) Rule
func (MaxLengthRule) Msg ¶
func (r MaxLengthRule) Msg(msg string) Rule
func (MaxLengthRule) Validate ¶
func (r MaxLengthRule) Validate(lang string, value interface{}) error
type MinLengthRule ¶
type MinLengthRule struct {
// contains filtered or unexported fields
}
func MinLenRune ¶
func MinLenRune(min int) MinLengthRule
func MinLength ¶
func MinLength(min int, rune bool) MinLengthRule
func (MinLengthRule) Code ¶
func (r MinLengthRule) Code(code string) Rule
func (MinLengthRule) Msg ¶
func (r MinLengthRule) Msg(msg string) Rule
func (MinLengthRule) Validate ¶
func (r MinLengthRule) Validate(lang string, value interface{}) error
type MultipleOfRule ¶
type MultipleOfRule struct {
// contains filtered or unexported fields
}
MultipleOfRule is a validation rule that checks if a value is a multiple of the "base" value.
func MultipleOf ¶
func MultipleOf(base interface{}) MultipleOfRule
MultipleOf returns a validation rule that checks if a value is a multiple of the "base" value. Note that "base" should be of integer type.
func (MultipleOfRule) Code ¶
func (r MultipleOfRule) Code(code string) Rule
func (MultipleOfRule) Error ¶
func (r MultipleOfRule) Error(message string) MultipleOfRule
Error sets the error message for the rule.
func (MultipleOfRule) ErrorObject ¶
func (r MultipleOfRule) ErrorObject(err Error) MultipleOfRule
ErrorObject sets the error struct for the rule.
func (MultipleOfRule) Msg ¶
func (r MultipleOfRule) Msg(msg string) Rule
func (MultipleOfRule) Validate ¶
func (r MultipleOfRule) Validate(lang string, value interface{}) error
Validate checks if the value is a multiple of the "base" value.
type NotInRule ¶
type NotInRule struct {
// contains filtered or unexported fields
}
NotInRule is a validation rule that checks if a value is absent from the given list of values.
func NotIn ¶
func NotIn(values ...interface{}) NotInRule
NotIn returns a validation rule that checks if a value is absent from the given list of values. Note that the value being checked and the possible range of values must be of the same type. An empty value is considered valid. Use the Required rule to make sure a value is not empty.
type RangeLengthRule ¶
type RangeLengthRule struct {
// contains filtered or unexported fields
}
RangeLengthRule is a validation rule that checks if a value's length is within the specified range.
func RangeLenRune ¶
func RangeLenRune(min, max int) RangeLengthRule
func RangeLength ¶
func RangeLength(min, max int, rune bool) RangeLengthRule
func (RangeLengthRule) Code ¶
func (r RangeLengthRule) Code(code string) Rule
func (RangeLengthRule) Msg ¶
func (r RangeLengthRule) Msg(msg string) Rule
func (RangeLengthRule) Validate ¶
func (r RangeLengthRule) Validate(lang string, value interface{}) error
Validate checks if the given value is valid or not.
type RequiredRule ¶
type RequiredRule struct {
// contains filtered or unexported fields
}
RequiredRule is a rule that checks if a value is not empty.
func (RequiredRule) Code ¶
func (r RequiredRule) Code(code string) Rule
func (RequiredRule) Msg ¶
func (r RequiredRule) Msg(msg string) Rule
func (RequiredRule) Validate ¶
func (r RequiredRule) Validate(lang string, value interface{}) error
Validate checks if the given value is valid or not.
func (RequiredRule) When ¶
func (r RequiredRule) When(condition bool) RequiredRule
When sets the condition that determines if the validation should be performed.
type Rule ¶
type Rule interface { // Validate validates a value and returns a value if validation fails. Validate(lang string, value interface{}) error Code(code string) Rule Msg(msg string) Rule }
Rule represents a validation rule.
func WithContext ¶
func WithContext(f RuleWithContextFunc) Rule
WithContext wraps a RuleWithContextFunc into a context-aware Rule.
type RuleFunc ¶
RuleFunc represents a validator function. You may wrap it as a Rule by calling By().
type RuleWithContext ¶
type RuleWithContext interface { // ValidateWithContext validates a value and returns a value if validation fails. ValidateWithContext(ctx context.Context, lang string, value interface{}) error }
RuleWithContext represents a context-aware validation rule.
type RuleWithContextFunc ¶
RuleWithContextFunc represents a validator function that is context-aware. You may wrap it as a Rule by calling WithContext().
type StringRule ¶
type StringRule struct {
// contains filtered or unexported fields
}
StringRule is a rule that checks a string variable using a specified stringValidator.
func String ¶
func String(validator stringValidator, err Error) StringRule
func StringCode ¶
func StringCode(validator stringValidator, code string) StringRule
func StringMsg ¶
func StringMsg(validator stringValidator, msg string) StringRule
func (StringRule) Code ¶
func (r StringRule) Code(code string) Rule
func (StringRule) Error ¶
func (r StringRule) Error(message string) StringRule
Error sets the error message for the rule.
func (StringRule) ErrorObject ¶
func (r StringRule) ErrorObject(err Error) StringRule
ErrorObject sets the error struct for the rule.
func (StringRule) Msg ¶
func (r StringRule) Msg(msg string) Rule
func (StringRule) Validate ¶
func (r StringRule) Validate(lang string, value interface{}) error
Validate checks if the given value is valid or not.
type Translator ¶
type Validatable ¶
type Validatable interface { // Validate validates the data and returns an error if validation fails. Validate(lang string) error }
Validatable is the interface indicating the type implementing it supports data validation.
type ValidatableWithContext ¶
type ValidatableWithContext interface { // ValidateWithContext validates the data with the given context and returns an error if validation fails. ValidateWithContext(ctx context.Context, lang string) error }
ValidatableWithContext is the interface indicating the type implementing it supports context-aware data validation.
type WhenRule ¶
type WhenRule struct {
// contains filtered or unexported fields
}
WhenRule is a validation rule that executes the given list of rules when the condition is true.
func When ¶
When returns a validation rule that executes the given list of rules when the condition is true.
func (WhenRule) Else ¶
Else returns a validation rule that executes the given list of rules when the condition is false.