Documentation
¶
Index ¶
- func IsBase64(s string) bool
- func IsBase64URL(s string) bool
- func IsBitcoinAddress(address string) bool
- func IsBitcoinBech32Address(address string) bool
- func IsByteLength(s string, min, max int) bool
- func IsCIDR(s string) bool
- func IsCIDRv4(s string) bool
- func IsCIDRv6(s string) bool
- func IsCRC32(s string) bool
- func IsCRC32b(s string) bool
- func IsCreditCard(s string) bool
- func IsDNSName(s string) bool
- func IsDataURI(s string) bool
- func IsDialString(s string) bool
- func IsDnsRFC1035Label(s string) bool
- func IsE164(s string) bool
- func IsEmail(s string) bool
- func IsExistingEmail(email string) bool
- func IsFQDN(s string) bool
- func IsFileName(s string) bool
- func IsHSLAColor(s string) bool
- func IsHSLColor(s string) bool
- func IsHash(s string, algorithm string) bool
- func IsHexColor(s string) bool
- func IsHost(s string) bool
- func IsHostnamePort(s string) bool
- func IsHostnameRFC1123(s string) bool
- func IsHostnameRFC952(s string) bool
- func IsHttpURL(s string) bool
- func IsHttpsURL(s string) bool
- func IsHttpxURL(s string) bool
- func IsIMEI(s string) bool
- func IsIMSI(s string) bool
- func IsIP(s string) bool
- func IsIP4AddrResolvable(s string) bool
- func IsIP6AddrResolvable(s string) bool
- func IsIPAddrResolvable(s string) bool
- func IsIPv4(s string) bool
- func IsIPv6(s string) bool
- func IsISBN(s string, version int) bool
- func IsISBN10(s string) bool
- func IsISBN13(s string) bool
- func IsJSON(s string) bool
- func IsJSONArray(s string) bool
- func IsJSONObject(s string) bool
- func IsJWT(s string) bool
- func IsLatitude(s string) bool
- func IsLongitude(s string) bool
- func IsMAC(s string) bool
- func IsMD4(s string) bool
- func IsMD5(s string) bool
- func IsMagnetURI(s string) bool
- func IsPort(s string) bool
- func IsRGBAColor(s string) bool
- func IsRGBColor(s string) bool
- func IsRequestURI(rawurl string) bool
- func IsRequestURL(rawurl string) bool
- func IsRipeMD128(s string) bool
- func IsRipeMD160(s string) bool
- func IsSHA1(s string) bool
- func IsSHA256(s string) bool
- func IsSHA384(s string) bool
- func IsSHA512(s string) bool
- func IsSSN(s string) bool
- func IsSemver(s string) bool
- func IsSwiftCode(s string) bool
- func IsTiger128(s string) bool
- func IsTiger160(s string) bool
- func IsTiger192(s string) bool
- func IsULID(s string) bool
- func IsURI(s string) bool
- func IsURL(s string) bool
- func IsURLWithScheme(s string, schemes ...string) bool
- func IsUUID(s string) bool
- func IsUUIDv3(s string) bool
- func IsUUIDv4(s string) bool
- func IsUUIDv5(s string) bool
- type CustomTypeFunc
- type FieldError
- type FieldLevel
- type FilterFunc
- type Func
- type FuncEx
- type InvalidValidationError
- type StructLevel
- type StructLevelFunc
- type TagNameFunc
- type Validate
- func (v *Validate) Field(field string, value any, tag string) (err error)
- func (v *Validate) Map(data map[string]any, rules map[string]any) map[string]any
- func (v *Validate) RegisterAlias(alias, tags string)
- func (v *Validate) RegisterCustomTypeFunc(fn CustomTypeFunc, types ...any)
- func (v *Validate) RegisterStructValidation(fn StructLevelFunc, types ...any)
- func (v *Validate) RegisterTagNameFunc(fn TagNameFunc)
- func (v *Validate) RegisterValidation(tag string, fn Func, callValidationEvenIfNull ...bool)
- func (v *Validate) RegisterValidationEx(tag string, fn FuncEx, callValidationEvenIfNull ...bool)
- func (v *Validate) SetTagName(name string)
- func (v *Validate) Struct(s any) (err error)
- func (v *Validate) StructExcept(s any, fields ...string) (err error)
- func (v *Validate) StructFiltered(s any, fn FilterFunc) (err error)
- func (v *Validate) StructPartial(s any, fields ...string) (err error)
- func (v *Validate) Var(value any, tag string) error
- func (v *Validate) VarWithValue(field any, other any, tag string) (err error)
- type ValidationErrors
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func IsBase64URL ¶
IsBase64URL checks if a string is base64 url safe encoded.
func IsBitcoinAddress ¶ added in v1.0.27
IsBitcoinAddress is the validation function for validating if the field's value is a valid btc address
func IsBitcoinBech32Address ¶ added in v1.0.27
IsBitcoinBech32Address is the validation function for validating if the field's value is a valid bech32 btc address
func IsByteLength ¶
IsByteLength checks if the string's length (in bytes) falls in a range.
func IsCreditCard ¶
IsCreditCard checks if the string is a credit card.
func IsDialString ¶
IsDialString validates the given string for usage with the various Dial() functions
func IsDnsRFC1035Label ¶ added in v1.0.27
IsDnsRFC1035Label is the validation function for validating if the current field's value is a valid dns RFC 1035 label, defined in RFC 1035.
func IsE164 ¶ added in v1.0.27
IsE164 is the validation function for validating if the current field's value is a valid e.164 formatted phone number.
func IsExistingEmail ¶
IsExistingEmail checks if the string is an email of existing domain
func IsHSLAColor ¶
IsHSLAColor checks if the string is a valid HSLA color in form hsla(0, 100%, 50%, 0.5).
func IsHSLColor ¶
IsHSLColor checks if the string is a valid HSLA color in form hsl(0, 100%, 50%).
func IsHash ¶
IsHash checks if a string is a hash of type algorithm. Algorithm is one of ['md4', 'md5', 'sha1', 'sha256', 'sha384', 'sha512', 'ripemd128', 'ripemd160', 'tiger128', 'tiger160', 'tiger192', 'crc32', 'crc32b']
func IsHexColor ¶
IsHexColor checks if the string is a hex decimal color.
func IsHostnamePort ¶ added in v1.0.27
func IsHostnameRFC1123 ¶ added in v1.0.27
func IsHostnameRFC952 ¶ added in v1.0.27
func IsHttpsURL ¶ added in v1.0.15
IsHttpsURL checks if the string is an https:// URL.
func IsHttpxURL ¶ added in v1.0.27
IsHttpxURL checks if the string is an https?:// URL.
func IsIP4AddrResolvable ¶
IsIP4AddrResolvable checks if the string is a resolvable ip v4 address.
func IsIP6AddrResolvable ¶
IsIP6AddrResolvable checks if the string is a resolvable ip v6 address.
func IsIPAddrResolvable ¶
IsIPAddrResolvable checks if the string is a resolvable ip address.
func IsISBN ¶
IsISBN checks if the string is an ISBN (version 10 or 13). If version value is not equal to 10 or 13, it will be checks both variants.
func IsJSONArray ¶ added in v1.0.27
func IsJSONObject ¶ added in v1.0.27
func IsLongitude ¶
IsLongitude checks if a string is valid longitude.
func IsMAC ¶
IsMAC checks if a string is valid MAC address. Possible MAC formats: 01:23:45:67:89:ab 01:23:45:67:89:ab:cd:ef 01-23-45-67-89-ab 01-23-45-67-89-ab-cd-ef 0123.4567.89ab 0123.4567.89ab.cdef
func IsMagnetURI ¶
IsMagnetURI checks if a string is valid magnet URI
func IsRGBAColor ¶
IsRGBAColor checks if the string is a valid RGBA color in form rgb(RRR, GGG, BBB).
func IsRGBColor ¶
IsRGBColor checks if the string is a valid RGB color in form rgb(RRR, GGG, BBB).
func IsRequestURI ¶
IsRequestURI checks if the string rawurl, assuming it was received in an HTTP request, is an absolute URI or an absolute path.
func IsRequestURL ¶
IsRequestURL checks if the string rawurl, assuming it was received in an HTTP request, is a valid URL confirm to RFC 3986
func IsRipeMD128 ¶
IsRipeMD128 checks is a string is a RipeMD128 hash. Alias for `IsHash(s, "ripemd128")`
func IsRipeMD160 ¶
IsRipeMD160 checks is a string is a RipeMD160 hash. Alias for `IsHash(s, "ripemd160")`
func IsSemver ¶ added in v1.0.27
IsSemver is the validation function for validating if the current field's value is a valid semver version, defined in Semantic Versioning 2.0.0
func IsSwiftCode ¶
IsSwiftCode checks if the string is a valid Business Identifier Code (SWIFT code), defined in ISO 9362
func IsTiger128 ¶
IsTiger128 checks is a string is a Tiger128 hash. Alias for `IsHash(s, "tiger128")`
func IsTiger160 ¶
IsTiger160 checks is a string is a Tiger160 hash. Alias for `IsHash(s, "tiger160")`
func IsTiger192 ¶
IsTiger192 checks is a string is a Tiger192 hash. Alias for `IsHash(s, "tiger192")`
func IsULID ¶ added in v1.0.27
IsULID is the validation function for validating if the field's value is a valid ULID.
func IsURLWithScheme ¶ added in v1.0.27
IsURLWithScheme checks if the string is an URL with specified shemes.
Types ¶
type CustomTypeFunc ¶
CustomTypeFunc allows for overriding or adding custom field type handler functions field = field value of the type to return a value to be validated example Valuer 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.
//
// eg. 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.
//
// eg. 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.
//
// eg. JSON name "User.fname"
//
// See StructNamespace() for a version that returns actual names.
//
// NOTE: this field can be blank when validating a single primitive field
// using validate.Field(...) as there is no way to extract it's name
Namespace() string
// StructNamespace returns the namespace for the field error, with the field's
// actual name.
//
// eq. "User.FirstName" see Namespace for comparison
//
// NOTE: this field can be blank 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.
//
// eq. JSON name "fname"
// see StructField for comparison
Field() string
// StructField returns the field's actual name from the struct, when able to determine.
//
// eq. "FirstName"
// see Field for comparison
StructField() string
// Value returns the actual field's value in case needed for creating the error
// message
Value() any
// Param returns the param value, in string form for comparison; this will also
// help with generating an error message
Param() string
// Kind returns the Field's reflect Kind
//
// eg. time.Time's kind is a struct
Kind() reflect.Kind
// Type returns the Field's reflect Type
//
// eg. time.Time's type is time.Time
Type() reflect.Type
// Error returns the FieldError's message
Error() string
// Cause returns the cause error
Cause() error
}
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 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.
//
// Deprecated: Use GetStructFieldOK2() instead which also return if the value is nullable.
GetStructFieldOK() (reflect.Value, reflect.Kind, 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.
//
// Deprecated: Use GetStructFieldOKAdvanced2() instead which also return if the value is nullable.
GetStructFieldOKAdvanced(val reflect.Value, namespace string) (reflect.Value, reflect.Kind, bool)
// GetStructFieldOK2 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.
GetStructFieldOK2() (reflect.Value, reflect.Kind, bool, bool)
// GetStructFieldOKAdvanced2 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.
GetStructFieldOKAdvanced2(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 StructFiltered(...) function. returning true results in the field being filtered/skipped from validation
type Func ¶
type Func func(fl FieldLevel) bool
Func accepts a FieldLevel interface for all validation needs.
type FuncEx ¶ added in v1.0.27
type FuncEx func(fl FieldLevel) error
FuncEx accepts a FieldLevel interface for all validation needs.
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 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 just by passing the field and tag information
//
// NOTES:
//
// fieldName and altName get appended to the existing namespace that
// validator is on. e.g. pass 'FirstName' or 'Names[0]' depending
// on the nesting
//
// tag can be an existing validation tag or just something you make up
// and process on the flip side it's up to you.
ReportError(field any, fieldName, structFieldName string, tag, param string, err error)
// ReportValidationErrors reports an error just by passing ValidationErrors
//
// NOTES:
//
// relativeNamespace and relativeActualNamespace get appended to the
// existing namespace that validator is on.
// e.g. 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 a struct
type StructLevelFunc ¶
type StructLevelFunc func(sl StructLevel)
StructLevelFunc accepts all values needed for struct level validation
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 ¶
func New() *Validate
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) Field ¶ added in v1.0.27
Field validates a single variable using tag style validation. eg. var i int validate.Field("a", i, "gt=1,lt=10")
WARNING: a struct can be passed for validation eg. 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. You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. validate Array, Slice and maps fields which may contain more than one error
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 validation to structs.
NOTE: this function 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 ...any)
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 ...any)
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) RegisterTagNameFunc ¶
func (v *Validate) RegisterTagNameFunc(fn TagNameFunc)
RegisterTagNameFunc registers a function to get alternate names for StructFields.
eg. 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) RegisterValidationEx ¶ added in v1.0.27
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) 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. You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors.
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. You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors.
func (*Validate) StructFiltered ¶
func (v *Validate) StructFiltered(s any, fn FilterFunc) (err 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. You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors.
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 eg. NestedStruct.Field or NestedArrayField[0].Struct.Name
It returns InvalidValidationError for bad values passed in and nil or ValidationErrors as error otherwise. You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors.
func (*Validate) Var ¶
Var validates a single variable using tag style validation. eg. var i int validate.Var(i, "gt=1,lt=10")
WARNING: a struct can be passed for validation eg. 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. You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. 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 eg. s1 := "abcd" s2 := "abcd" validate.VarWithValue(s1, s2, "eqcsfield") // returns true
WARNING: a struct can be passed for validation eg. 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. You will need to assert the error if it's not nil eg. err.(validator.ValidationErrors) to access the array of errors. 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) As ¶ added in v1.0.17
func (ves ValidationErrors) As(err any) bool
func (ValidationErrors) Error ¶
func (ves 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 your application is contained within the FieldError found within the ValidationErrors array
func (ValidationErrors) Unwrap ¶ added in v1.0.17
func (ves ValidationErrors) Unwrap() []error
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
_examples
|
|
|
custom
command
|
|
|
custom-validation
command
|
|
|
dive
command
|
|
|
map-validation
command
|
|
|
simple
command
|
|
|
struct-level
command
|