Documentation
¶
Index ¶
- type CustomTypeFunc
- type FieldError
- type FieldLevel
- type FilterFunc
- type Func
- type FuncCtx
- type InvalidValidationError
- type Option
- type StructLevel
- type StructLevelFunc
- type StructLevelFuncCtx
- type TagNameFunc
- type Validate
- func (v *Validate) RegisterAlias(alias, tags string)
- func (v *Validate) RegisterCustomTypeFunc(fn CustomTypeFunc, types ...interface{})
- func (v *Validate) RegisterStructValidation(fn StructLevelFunc, types ...interface{})
- func (v *Validate) RegisterStructValidationCtx(fn StructLevelFuncCtx, types ...interface{})
- func (v *Validate) RegisterStructValidationMapRules(rules map[string]string, types ...interface{})
- func (v *Validate) RegisterTagNameFunc(fn TagNameFunc)
- func (v *Validate) RegisterValidation(tag string, fn Func, callValidationEvenIfNull ...bool) error
- func (v *Validate) RegisterValidationCtx(tag string, fn FuncCtx, callValidationEvenIfNull ...bool) error
- func (v *Validate) SetTagName(name string)
- func (v *Validate) Struct(s interface{}) error
- func (v *Validate) StructCtx(ctx context.Context, s interface{}) (err error)
- func (v *Validate) StructExcept(s interface{}, fields ...string) error
- func (v *Validate) StructExceptCtx(ctx context.Context, s interface{}, fields ...string) (err error)
- func (v *Validate) StructFiltered(s interface{}, fn FilterFunc) error
- func (v *Validate) StructFilteredCtx(ctx context.Context, s interface{}, fn FilterFunc) (err error)
- func (v *Validate) StructPartial(s interface{}, fields ...string) error
- func (v *Validate) StructPartialCtx(ctx context.Context, s interface{}, fields ...string) (err error)
- func (v *Validate) ValidateMap(data map[string]interface{}, rules map[string]interface{}) map[string]interface{}
- func (v Validate) ValidateMapCtx(ctx context.Context, data map[string]interface{}, rules map[string]interface{}) map[string]interface{}
- func (v *Validate) Var(field interface{}, tag string) error
- func (v *Validate) VarCtx(ctx context.Context, field interface{}, tag string) (err error)
- func (v *Validate) VarWithValue(field interface{}, other interface{}, tag string) error
- func (v *Validate) VarWithValueCtx(ctx context.Context, field interface{}, other interface{}, tag string) (err error)
- type ValidationErrors
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type CustomTypeFunc ¶
CustomTypeFunc overrides or adds custom field type handler functions field = field type value to return a value to validate Valuer example from sql drive see https://golang.org/src/database/sql/driver/types.go?s=1210:1293#L29
type FieldError ¶
type FieldError interface { // Tag returns the validation tag that failed. // If the validation was an alias, // this will return the alias name and not the underlying tag that failed. // For example, alias "iscolor": "hexcolor|rgb|rgba|hsl|hsla" will return "iscolor" Tag() string // ActualTag returns the validation tag that failed, // even if an alias the actual tag within the alias will be returned. // If an 'or' validation fails the entire or will be returned. // For example, alias "iscolor": "hexcolor|rgb|rgba|hsl|hsla" will return "hexcolor|rgb|rgba|hsl|hsla" ActualTag() string // Namespace returns the namespace for the field error, // with the tag name taking precedence over the field's actual name. // For example, JSON name "User.fname" // // See StructNamespace() for a version that returns actual names. // // NOTE: this field may be empty when validating a single primitive field using validate.Field(...), // as there is no way to extract its name. Namespace() string // StructNamespace returns the namespace for the field error, with the field's actual name. // For example, "User.FirstName" see Namespace for comparison // // NOTE: this field may be empty when validating a single primitive field using validate.Field(...), // as there is no way to extract its name. StructNamespace() string // Field returns the fields name with the tag name taking precedence over the field's actual name. // // `RegisterTagNameFunc` must be registered to get tag value. // For example, JSON name "fname" see StructField for comparison, Field() string // StructField returns the field's actual name from the struct, when able to determine. // For example, "FirstName" see Field for comparison StructField() string // Value returns the actual field's value in case needed for creating the error message. Value() interface{} // Param returns the parameter value as a string for comparison. // This will also help when generating an error message. Param() string // Kind returns the Field's reflect Kind. // For example, time.Time's kind is a struct Kind() reflect.Kind // Type returns the Field's reflect Type. // For example, time.Time's type is time.Time Type() reflect.Type // Error returns the FieldError's message. Error() string }
FieldError contains all functions to get error details.
type FieldLevel ¶
type FieldLevel interface { // Top returns the top level struct, if any Top() reflect.Value // Parent returns the current fields parent struct, // if any or the comparison value if called 'VarWithValue' Parent() reflect.Value // Field returns current field for validation Field() reflect.Value // FieldName returns the field's name with the tag // name taking precedence over the fields actual name. FieldName() string // StructFieldName returns the struct field's name StructFieldName() string // Param returns param for validation against current field Param() string // GetTag returns the current validations tag name GetTag() string // ExtractType gets the actual underlying type of field value. // It will dive into pointers, // customTypes and return you the underlying value and it's kind. ExtractType(field reflect.Value) (value reflect.Value, kind reflect.Kind, nullable bool) // GetStructFieldOK traverses the parent struct to retrieve a specific field denoted by the provided namespace // in the param and returns the field, field kind, // if it's a nullable type and whether is was successful in retrieving the field at all. // // NOTE: when not successful ok will be false, // this can happen when a nested struct is nil and so the field could not be retrieved because it didn't exist. GetStructFieldOK() (reflect.Value, reflect.Kind, bool, bool) // GetStructFieldOKAdvanced is the same as GetStructFieldOK except that it accepts the // parent struct to start looking for the field and namespace allowing more extensibility for validators. GetStructFieldOKAdvanced(val reflect.Value, namespace string) (reflect.Value, reflect.Kind, bool, bool) }
FieldLevel contains all the information and helper functions to validate a field.
type FilterFunc ¶
FilterFunc is the type used to filter fields using the StructFiltered(...) function. Return true causes the field to be filtered/skipped on validation.
type Func ¶
type Func func(fl FieldLevel) bool
Func accepts a FieldLevel interface for all validation needs. Return value should be true when validation succeeds.
type FuncCtx ¶
type FuncCtx func(ctx context.Context, fl FieldLevel) bool
FuncCtx accepts a context.Context and FieldLevel interface for all validation needs. The return value should be true when validation succeeds.
type InvalidValidationError ¶
InvalidValidationError describes an invalid argument passed to `Struct`, `StructExcept`, StructPartial` or `Field`.
func (*InvalidValidationError) Error ¶
func (e *InvalidValidationError) Error() string
Error returns InvalidValidationError message.
type Option ¶
type Option func(*Validate)
Option represents a configurations option to be applied to validator during initialization.
func WithPrivateFieldValidation ¶
func WithPrivateFieldValidation() Option
WithPrivateFieldValidation activates validation for unexported fields using of the `unsafe` package.
WARNING: By using this feature, you acknowledge that you are aware of the risks and accept any current or future consequences of using this feature.
func WithRequiredStructEnabled ¶
func WithRequiredStructEnabled() Option
WithRequiredStructEnabled enables required tag on non-pointer structs to be applied instead of ignored.
This was made opt-in behaviour in order to maintain backward compatibility with the behaviour previous to being able to apply struct level validations on struct fields directly.
NOTE: It is recommended to enabled this.
type StructLevel ¶
type StructLevel interface { // Validator returns the main validation object, in case one wants to call validations internally. // this is so you don't have to use anonymous functions to get access to the validate instance. Validator() *Validate // Top returns the top level struct, if any. Top() reflect.Value // Parent returns the current fields parent struct, if any. Parent() reflect.Value // Current returns the current struct. Current() reflect.Value // ExtractType gets the actual underlying type of field value. // It will dive into pointers, // customTypes and return you the underlying value and its kind. ExtractType(field reflect.Value) (value reflect.Value, kind reflect.Kind, nullable bool) // ReportError reports an error by simply passing field and tag information. // // fieldName and structFieldName are appended to the existing namespace that the validator resides on. // For example, could pass 'FirstName' or 'Names[0]' depending on the nesting. // // tag can be an existing validation tag or an arbitrary tag (needs handling). ReportError(field interface{}, fieldName, structFieldName string, tag, param string) // ReportValidationErrors reports an error just by passing ValidationErrors. // // relativeNamespace and relativeActualNamespace get appended to the existing namespace that validator is on. // For example, could pass 'User.FirstName' or 'Users[0].FirstName' depending on the nesting. // Most of the time they will be blank, unless you validate at a level lower the current field depth. ReportValidationErrors(relativeNamespace, relativeActualNamespace string, errs ValidationErrors) }
StructLevel contains all the information and helper functions to validate the structure.
type StructLevelFunc ¶
type StructLevelFunc func(sl StructLevel)
StructLevelFunc accepts all values needed for struct level validation.
type StructLevelFuncCtx ¶
type StructLevelFuncCtx func(ctx context.Context, sl StructLevel)
StructLevelFuncCtx accepts all values needed for struct level validation but also allows passing of contextual validation information via context.Context.
type TagNameFunc ¶
type TagNameFunc func(field reflect.StructField) string
TagNameFunc allows for adding of a custom tag name parser.
type Validate ¶
type Validate struct {
// contains filtered or unexported fields
}
Validate contains the validator settings and cache.
func New ¶
New returns a new instance of 'validate' with sane defaults. Validate is designed to be thread-safe and used as a singleton instance. It caches information about your struct and validations, in essence only parsing your validation tags once per struct type. Using multiple instances neglects the benefit of caching.
func (*Validate) RegisterAlias ¶
RegisterAlias registers a mapping of a single validation tag that defines a common or complex set of validation(s) to simplify adding validations to structures.
NOTE: this method is not thread-safe it is intended that these all be registered prior to any validation.
func (*Validate) RegisterCustomTypeFunc ¶
func (v *Validate) RegisterCustomTypeFunc(fn CustomTypeFunc, types ...interface{})
RegisterCustomTypeFunc registers a CustomTypeFunc against a number of types.
NOTE: this method is not thread-safe it is intended that these all be registered prior to any validation.
func (*Validate) RegisterStructValidation ¶
func (v *Validate) RegisterStructValidation(fn StructLevelFunc, types ...interface{})
RegisterStructValidation registers a StructLevelFunc against a number of types.
NOTE: this method is not thread-safe it is intended that these all be registered prior to any validation.
func (*Validate) RegisterStructValidationCtx ¶
func (v *Validate) RegisterStructValidationCtx(fn StructLevelFuncCtx, types ...interface{})
RegisterStructValidationCtx registers a StructLevelFuncCtx against a number of types and allows passing of contextual validation information vis context.Context.
NOTE: this method is not thread-safe it is intended that these all be registered prior to any validation.
func (*Validate) RegisterStructValidationMapRules ¶
RegisterStructValidationMapRules registers validate map rules. Be aware that map validation rules supersede those defined on a/the struct if present.
NOTE: this method is not thread-safe it is intended that these all be registered prior to any validation
func (*Validate) RegisterTagNameFunc ¶
func (v *Validate) RegisterTagNameFunc(fn TagNameFunc)
RegisterTagNameFunc registers a function to get alternate names for StructFields. For example, to use the names which have been specified for JSON representations of structs, rather than normal Go field names:
validate.RegisterTagNameFunc(func(fld reflect.StructField) string { name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0] // skip if tag key says it should be ignored if name == "-" { return "" } return name })
func (*Validate) RegisterValidation ¶
RegisterValidation adds a validation with the given tag.
NOTES: If the key already exists, the previous validation function will be replaced. This method is not thread-safe it is intended that these all be registered prior to any validation.
func (*Validate) RegisterValidationCtx ¶
func (v *Validate) RegisterValidationCtx(tag string, fn FuncCtx, callValidationEvenIfNull ...bool) error
RegisterValidationCtx does the same as RegisterValidation on accepts a FuncCtx validation allowing context.Context validation support.
func (*Validate) SetTagName ¶
SetTagName allows for changing of the default tag name of 'validate'.
func (*Validate) Struct ¶
Struct validates a structs exposed fields, and automatically validates nested structs, unless otherwise specified.
It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. To access the error array, assert the error unless it is nil, e. g. err.(validator.ValidationErrors).
func (*Validate) StructCtx ¶
StructCtx validates a structs exposed fields, and automatically validates nested structs, unless otherwise specified and also allows passing of context.Context for contextual validation information.
It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. To access the error array, assert the error unless it is nil, e. g. err.(validator.ValidationErrors).
func (*Validate) StructExcept ¶
StructExcept validates all fields except the ones passed in. Fields may be provided in a namespaced fashion relative to the struct provided i. e. NestedStruct.Field or NestedArrayField[0].Struct.Name
It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. To access the error array, assert the error unless it is nil, e. g. err.(validator.ValidationErrors).
func (*Validate) StructExceptCtx ¶
func (v *Validate) StructExceptCtx(ctx context.Context, s interface{}, fields ...string) (err error)
StructExceptCtx validates all fields except the ones passed in and allows passing of contextual validation information vis context.Context. Fields may be provided in a namespaced fashion relative to the struct provided i. e. NestedStruct.Field or NestedArrayField[0].Struct.Name
It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. To access the error array, assert the error unless it is nil, e. g. err.(validator.ValidationErrors).
func (*Validate) StructFiltered ¶
func (v *Validate) StructFiltered(s interface{}, fn FilterFunc) error
StructFiltered validates a structs exposed fields, that pass the FilterFunc check and automatically validates nested structs, unless otherwise specified.
It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. To access the error array, assert the error unless it is nil, e. g. err.(validator.ValidationErrors).
func (*Validate) StructFilteredCtx ¶
func (v *Validate) StructFilteredCtx(ctx context.Context, s interface{}, fn FilterFunc) (err error)
StructFilteredCtx validates a structs exposed fields, that pass the FilterFunc check and automatically validates nested structs, unless otherwise specified and also allows passing of contextual validation information vis context.Context.
It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. To access the error array, assert the error unless it is nil, e. g. err.(validator.ValidationErrors).
func (*Validate) StructPartial ¶
StructPartial validates the fields passed in only, ignoring all others. Fields may be provided in a namespaced fashion relative to the struct provided e. g. NestedStruct.Field or NestedArrayField[0].Struct.Name
It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. To access the error array, assert the error unless it is nil, e. g. err.(validator.ValidationErrors).
func (*Validate) StructPartialCtx ¶
func (v *Validate) StructPartialCtx(ctx context.Context, s interface{}, fields ...string) (err error)
StructPartialCtx validates the fields passed in only, ignoring all others and allows passing of contextual validation information vis context.Context. Fields may be provided in a namespaced fashion relative to the struct provided e. g. NestedStruct.Field or NestedArrayField[0].Struct.Name.
It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. To access the error array, assert the error unless it is nil, e. g. err.(validator.ValidationErrors).
func (*Validate) ValidateMap ¶
func (v *Validate) ValidateMap(data map[string]interface{}, rules map[string]interface{}) map[string]interface{}
ValidateMap validates map data from a map of tags.
func (Validate) ValidateMapCtx ¶
func (v Validate) ValidateMapCtx(ctx context.Context, data map[string]interface{}, rules map[string]interface{}) map[string]interface{}
ValidateMapCtx validates a map using a map of validation rules and allows passing of contextual validation information vis context.Context.
func (*Validate) Var ¶
Var validates a single variable using tag style validation. E. g.
var i int validate.Var(i, "gt=1,lt=10")
WARNING: a struct can be passed for validation, e. g. time.Time is a struct or if you have a custom type and have registered a custom type handler, so must allow it. However unforeseen validations will occur if trying to validate a struct that is meant to be passed to 'validate.Struct'.
It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. To access the error array, assert the error unless it is nil, e. g. err.(validator.ValidationErrors). Validate Array, Slice and maps fields which may contain more than one error
func (*Validate) VarCtx ¶
VarCtx validates a single variable using tag style validation and allows passing of contextual validation information vis context.Context. E. g.
var i int validate.Var(i, "gt=1,lt=10")
WARNING: a struct can be passed for validation, e. g. time.Time is a struct or if you have a custom type and have registered a custom type handler, so must allow it. However unforeseen validations will occur if trying to validate a struct that is meant to be passed to 'validate.Struct'.
It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. To access the error array, assert the error unless it is nil, e. g. err.(validator.ValidationErrors). Validate Array, Slice and maps fields which may contain more than one error.
func (*Validate) VarWithValue ¶
VarWithValue validates a single variable, against another variable/field's value using tag style validation. E. g.
s1 := "abcd" s2 := "abcd" validate.VarWithValue(s1, s2, "eqcsfield") // returns true
WARNING: a struct can be passed for validation, e. g. time.Time is a struct or if you have a custom type and have registered a custom type handler, so must allow it. However unforeseen validations will occur if trying to validate a struct that is meant to be passed to 'validate.Struct'
It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. To access the error array, assert the error unless it is nil, e. g. err.(validator.ValidationErrors). Validate Array, Slice and maps fields which may contain more than one error
func (*Validate) VarWithValueCtx ¶
func (v *Validate) VarWithValueCtx(ctx context.Context, field interface{}, other interface{}, tag string) (err error)
VarWithValueCtx validates a single variable, against another variable/field's value using tag style validation and allows passing of contextual validation information vis context.Context. E. g.
s1 := "abcd" s2 := "abcd" validate.VarWithValue(s1, s2, "eqcsfield") // returns true
WARNING: a struct can be passed for validation, e. g. time.Time is a struct or if you have a custom type and have registered a custom type handler, so must allow it. However unforeseen validations will occur if trying to validate a struct that is meant to be passed to 'validate.Struct'.
It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. To access the error array, assert the error unless it is nil, e. g. err.(validator.ValidationErrors). Validate Array, Slice and maps fields which may contain more than one error
type ValidationErrors ¶
type ValidationErrors []FieldError
ValidationErrors is an array of FieldError's for use in custom error messages post validation.
func (ValidationErrors) Error ¶
func (ve ValidationErrors) Error() string
Error is intended for use in development + debugging and not intended to be a production error message. It allows ValidationErrors to subscribe to the Error interface. All information to create an error message specific to application is contained within the FieldError found within the ValidationErrors array.