vad

package
v1.0.18 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 3, 2024 License: MIT Imports: 18 Imported by: 4

README

Package validator

Package vad implements value validations for structs and individual fields based on tags.

It has the following unique features:

  • Cross Field and Cross Struct validations by using validation tags or custom validators.
  • Slice, Array and Map diving, which allows any or all levels of a multidimensional field to be validated.
  • Ability to dive into both map keys and values for validation
  • Handles type interface by determining it's underlying type prior to validation.
  • Handles custom field types such as sql driver Valuer see Valuer
  • Alias validation tags, which allows for mapping of several validations to a single tag for easier defining of validations on structs
  • Extraction of custom defined Field Name e.g. can specify to extract the JSON name while validating and have it available in the resulting FieldError

Installation

Use go get.

go get github.com/askasoft/pango

Then import the validator package into your own code.

import "github.com/askasoft/pango/vad"

Error Return Value

Validation functions return type error

They return type error to avoid the issue discussed in the following, where err is always != nil:

Validator returns only InvalidValidationError for bad validation input, nil or ValidationErrors as type error; so, in your code all you need to do is check if the error returned is not nil, and if it's not check if error is InvalidValidationError ( if necessary, most of the time it isn't ) type cast it to type ValidationErrors like so:

err := validate.Struct(mystruct)
validationErrors := err.(vad.ValidationErrors)

Usage and documentation

Examples:

Baked-in Validations

Fields:
Tag Description
eqcsfield Field Equals Another Field (relative)
eqfield Field Equals Another Field
fieldcontains NOT DOCUMENTED IN doc.go
fieldexcludes NOT DOCUMENTED IN doc.go
gtcsfield Field Greater Than Another Relative Field
gtecsfield Field Greater Than or Equal To Another Relative Field
gtefield Field Greater Than or Equal To Another Field
gtfield Field Greater Than Another Field
ltcsfield Less Than Another Relative Field
ltecsfield Less Than or Equal To Another Relative Field
ltefield Less Than or Equal To Another Field
ltfield Less Than Another Field
necsfield Field Does Not Equal Another Field (relative)
nefield Field Does Not Equal Another Field
Network:
Tag Description
cidr Classless Inter-Domain Routing CIDR
cidrv4 Classless Inter-Domain Routing CIDRv4
cidrv6 Classless Inter-Domain Routing CIDRv6
datauri Data URL
fqdn Full Qualified Domain Name (FQDN)
hostname Hostname RFC 952
hostname_port HostPort
hostname_rfc1123 Hostname RFC 1123
ip Internet Protocol Address IP
ip4_addr Internet Protocol Address IPv4
ip6_addr Internet Protocol Address IPv6
ip_addr Internet Protocol Address IP
ipv4 Internet Protocol Address IPv4
ipv6 Internet Protocol Address IPv6
mac Media Access Control Address MAC
tcp4_addr Transmission Control Protocol Address TCPv4
tcp6_addr Transmission Control Protocol Address TCPv6
tcp_addr Transmission Control Protocol Address TCP
udp4_addr User Datagram Protocol Address UDPv4
udp6_addr User Datagram Protocol Address UDPv6
udp_addr User Datagram Protocol Address UDP
unix_addr Unix domain socket end point Address
uri URI String
url URL String
httpurl URL (https?://) String
httpsurl URL (https://) String
Strings:
Tag Description
alpha Alpha Only
alphanum Alphanumeric
alphanumunicode Alphanumeric Unicode
alphaunicode Alpha Unicode
ascii ASCII
boolean Boolean
contains Contains
containsany Contains Any
containsrune Contains Rune
endsnotwith Ends With
endswith Ends With
excludes Excludes
excludesall Excludes All
excludesrune Excludes Rune
lowercase Lowercase
multibyte Multi-Byte Characters
number NOT DOCUMENTED IN doc.go
numeric Numeric
decimal Decimal
printascii Printable ASCII
startsnotwith Starts Not With
startswith Starts With
uppercase Uppercase
Format:
Tag Description
base64 Base64 String
base64url Base64URL String
bic Business Identifier Code (ISO 9362)
bcp47_language_tag Language tag (BCP 47)
btc_addr Bitcoin Address
btc_addr_bech32 Bitcoin Bech32 Address (segwit)
datetime Datetime
duration Duration
e164 e164 formatted phone number
email E-mail String
eth_addr Ethereum Address
hexadecimal Hexadecimal String
hexcolor Hexcolor String
hsl HSL String
hsla HSLA String
html HTML Tags
html_encoded HTML Encoded
isbn International Standard Book Number
isbn10 International Standard Book Number 10
isbn13 International Standard Book Number 13
iso3166_1_alpha2 Two-letter country code (ISO 3166-1 alpha-2)
iso3166_1_alpha3 Three-letter country code (ISO 3166-1 alpha-3)
iso3166_1_alpha_numeric Numeric country code (ISO 3166-1 numeric)
iso3166_2 Country subdivision code (ISO 3166-2)
iso4217 Currency code (ISO 4217)
json JSON
jwt JSON Web Token (JWT)
latitude Latitude
longitude Longitude
postcode_iso3166_alpha2 Postcode
postcode_iso3166_alpha2_field Postcode
rgb RGB String
rgba RGBA String
ssn Social Security Number SSN
timezone Timezone
uuid Universally Unique Identifier UUID
uuid3 Universally Unique Identifier UUID v3
uuid3_rfc4122 Universally Unique Identifier UUID v3 RFC4122
uuid4 Universally Unique Identifier UUID v4
uuid4_rfc4122 Universally Unique Identifier UUID v4 RFC4122
uuid5 Universally Unique Identifier UUID v5
uuid5_rfc4122 Universally Unique Identifier UUID v5 RFC4122
uuid_rfc4122 Universally Unique Identifier UUID RFC4122
semver Semantic Versioning 2.0.0
ulid Universally Unique Lexicographically Sortable Identifier ULID
Comparisons:
Tag Description
eq Equals
ne Not Equal
gt Greater than
gte Greater than or equal
min Greater than or equal
lt Less Than
lte Less Than or Equal
max Less Than or Equal
btw Between
Length:
Tag Description
len (string's rune count, slice/map length) Equal
maxlen (string's rune count, slice/map length) Maximum
minlen (string's rune count, slice/map length) Minimum
btwlen (string's rune count, slice/map length) Between
Other:
Tag Description
dir Directory
file File path
isdefault Is Default
oneof One Of
required Required
required_if Required If
required_unless Required Unless
required_with Required With
required_with_all Required With All
required_without Required Without
required_without_all Required Without All
excluded_with Excluded With
excluded_with_all Excluded With All
excluded_without Excluded Without
excluded_without_all Excluded Without All
unique Unique
regexp Regular Expression Match
Aliases:
Tag Description
iscolor hexcolor|rgb|rgba|hsl|hsla

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsBase64

func IsBase64(s string) bool

IsBase64 checks if a string is base64 encoded.

func IsBase64URL

func IsBase64URL(s string) bool

IsBase64URL checks if a string is base64 url safe encoded.

func IsByteLength

func IsByteLength(s string, min, max int) bool

IsByteLength checks if the string's length (in bytes) falls in a range.

func IsCIDR

func IsCIDR(s string) bool

IsCIDR checks if a string is a valid v4 or v6 CIDR address.

func IsCIDRv4

func IsCIDRv4(s string) bool

IsCIDRv4 checks if a string is a valid v4 CIDR address.

func IsCIDRv6

func IsCIDRv6(s string) bool

IsCIDRv6 checks if a string is a valid v6 CIDR address.

func IsCRC32

func IsCRC32(s string) bool

IsCRC32 checks is a string is a CRC32 hash. Alias for `IsHash(s, "crc32")`

func IsCRC32b

func IsCRC32b(s string) bool

IsCRC32b checks is a string is a CRC32b hash. Alias for `IsHash(s, "crc32b")`

func IsCreditCard

func IsCreditCard(s string) bool

IsCreditCard checks if the string is a credit card.

func IsDNSName

func IsDNSName(s string) bool

IsDNSName will validate the given string as a DNS name

func IsDataURI

func IsDataURI(s string) bool

IsDataURI checks if a string is base64 encoded data URI such as an image

func IsDialString

func IsDialString(s string) bool

IsDialString validates the given string for usage with the various Dial() functions

func IsEmail

func IsEmail(s string) bool

IsEmail checks if the string is an email.

func IsExistingEmail

func IsExistingEmail(email string) bool

IsExistingEmail checks if the string is an email of existing domain

func IsFileName

func IsFileName(s string) bool

IsFileName is illegal file name

func IsHSLAColor

func IsHSLAColor(s string) bool

IsHSLAColor checks if the string is a valid HSLA color in form hsla(0, 100%, 50%, 0.5).

func IsHSLColor

func IsHSLColor(s string) bool

IsHSLColor checks if the string is a valid HSLA color in form hsl(0, 100%, 50%).

func IsHash

func IsHash(s string, algorithm string) bool

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

func IsHexColor(s string) bool

IsHexColor checks if the string is a hex decimal color.

func IsHost

func IsHost(s string) bool

IsHost checks if the string is a valid IP (both v4 and v6) or a valid DNS name

func IsHttpURL added in v1.0.15

func IsHttpURL(s string) bool

IsHttpURL checks if the string is an https?:// URL.

func IsHttpsURL added in v1.0.15

func IsHttpsURL(s string) bool

IsHttpsURL checks if the string is an https:// URL.

func IsIMEI

func IsIMEI(s string) bool

IsIMEI checks if a string is valid IMEI

func IsIMSI

func IsIMSI(s string) bool

IsIMSI checks if a string is valid IMSI

func IsIP

func IsIP(s string) bool

IsIP checks if a string is either IP version 4 or 6. Alias for `net.ParseIP`

func IsIP4AddrResolvable

func IsIP4AddrResolvable(s string) bool

IsIP4AddrResolvable checks if the string is a resolvable ip v4 address.

func IsIP6AddrResolvable

func IsIP6AddrResolvable(s string) bool

IsIP6AddrResolvable checks if the string is a resolvable ip v6 address.

func IsIPAddrResolvable

func IsIPAddrResolvable(s string) bool

IsIPAddrResolvable checks if the string is a resolvable ip address.

func IsIPv4

func IsIPv4(s string) bool

IsIPv4 checks if the string is an IP version 4.

func IsIPv6

func IsIPv6(s string) bool

IsIPv6 checks if the string is an IP version 6.

func IsISBN

func IsISBN(s string, version int) bool

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 IsISBN10

func IsISBN10(s string) bool

IsISBN10 checks if the string is an ISBN version 10.

func IsISBN13

func IsISBN13(s string) bool

IsISBN13 checks if the string is an ISBN version 13.

func IsJSON

func IsJSON(s string) bool

IsJSON checks if the string is valid JSON (note: uses json.Unmarshal).

func IsJWT

func IsJWT(s string) bool

IsJWT checks if the string is a valid JWT string.

func IsLatitude

func IsLatitude(s string) bool

IsLatitude checks if a string is valid latitude.

func IsLongitude

func IsLongitude(s string) bool

IsLongitude checks if a string is valid longitude.

func IsMAC

func IsMAC(s string) bool

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 IsMD4

func IsMD4(s string) bool

IsMD4 checks is a string is a MD4 hash. Alias for `IsHash(s, "md4")`

func IsMD5

func IsMD5(s string) bool

IsMD5 checks is a string is a MD5 hash. Alias for `IsHash(s, "md5")`

func IsMagnetURI

func IsMagnetURI(s string) bool

IsMagnetURI checks if a string is valid magnet URI

func IsPort

func IsPort(s string) bool

IsPort checks if a string represents a valid port

func IsRGBAColor

func IsRGBAColor(s string) bool

IsRGBAColor checks if the string is a valid RGBA color in form rgb(RRR, GGG, BBB).

func IsRGBColor

func IsRGBColor(s string) bool

IsRGBColor checks if the string is a valid RGB color in form rgb(RRR, GGG, BBB).

func IsRequestURI

func IsRequestURI(rawurl string) bool

IsRequestURI checks if the string rawurl, assuming it was received in an HTTP request, is an absolute URI or an absolute path.

func IsRequestURL

func IsRequestURL(rawurl string) bool

IsRequestURL checks if the string rawurl, assuming it was received in an HTTP request, is a valid URL confirm to RFC 3986

func IsRipeMD128

func IsRipeMD128(s string) bool

IsRipeMD128 checks is a string is a RipeMD128 hash. Alias for `IsHash(s, "ripemd128")`

func IsRipeMD160

func IsRipeMD160(s string) bool

IsRipeMD160 checks is a string is a RipeMD160 hash. Alias for `IsHash(s, "ripemd160")`

func IsSHA1

func IsSHA1(s string) bool

IsSHA1 checks is a string is a SHA-1 hash. Alias for `IsHash(s, "sha1")`

func IsSHA256

func IsSHA256(s string) bool

IsSHA256 checks is a string is a SHA256 hash. Alias for `IsHash(s, "sha256")`

func IsSHA384

func IsSHA384(s string) bool

IsSHA384 checks is a string is a SHA384 hash. Alias for `IsHash(s, "sha384")`

func IsSHA512

func IsSHA512(s string) bool

IsSHA512 checks is a string is a SHA512 hash. Alias for `IsHash(s, "sha512")`

func IsSSN

func IsSSN(s string) bool

IsSSN checks if the string is a valid SSN string.

func IsSwiftCode

func IsSwiftCode(s string) bool

IsSwiftCode checks if the string is a valid Business Identifier Code (SWIFT code), defined in ISO 9362

func IsTiger128

func IsTiger128(s string) bool

IsTiger128 checks is a string is a Tiger128 hash. Alias for `IsHash(s, "tiger128")`

func IsTiger160

func IsTiger160(s string) bool

IsTiger160 checks is a string is a Tiger160 hash. Alias for `IsHash(s, "tiger160")`

func IsTiger192

func IsTiger192(s string) bool

IsTiger192 checks is a string is a Tiger192 hash. Alias for `IsHash(s, "tiger192")`

func IsURI added in v1.0.15

func IsURI(s string) bool

IsURI checks if the string is an URI.

func IsURL

func IsURL(s string) bool

IsURL checks if the string is an URL.

func IsUUID

func IsUUID(s string) bool

IsUUID checks if the string is a UUID (version 3, 4 or 5).

func IsUUIDv3

func IsUUIDv3(s string) bool

IsUUIDv3 checks if the string is a UUID version 3.

func IsUUIDv4

func IsUUIDv4(s string) bool

IsUUIDv4 checks if the string is a UUID version 4.

func IsUUIDv5

func IsUUIDv5(s string) bool

IsUUIDv5 checks if the string is a UUID version 5.

Types

type CustomTypeFunc

type CustomTypeFunc func(field reflect.Value) any

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
}

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

type FilterFunc func(ns []byte) bool

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. The 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

type InvalidValidationError struct {
	Type reflect.Type
}

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)

	// 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 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 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

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) RegisterAlias

func (v *Validate) RegisterAlias(alias, tags string)

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) RegisterStructValidationCtx

func (v *Validate) RegisterStructValidationCtx(fn StructLevelFuncCtx, types ...any)

RegisterStructValidationCtx registers a StructLevelFuncCtx against a number of types and allows passing of contextual validation information via context.Context.

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]
    if name == "-" {
        return ""
    }
    return name
})

func (*Validate) RegisterValidation

func (v *Validate) RegisterValidation(tag string, fn Func, callValidationEvenIfNull ...bool)

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)

RegisterValidationCtx does the same as RegisterValidation on accepts a FuncCtx validation allowing context.Context validation support.

func (*Validate) SetTagName

func (v *Validate) SetTagName(name string)

SetTagName allows for changing of the default tag name of 'validate'

func (*Validate) Struct

func (v *Validate) Struct(s any) error

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) StructCtx

func (v *Validate) StructCtx(ctx context.Context, s any) (err error)

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. 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

func (v *Validate) StructExcept(s any, fields ...string) error

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) StructExceptCtx

func (v *Validate) StructExceptCtx(ctx context.Context, s any, fields ...string) (err error)

StructExceptCtx validates all fields except the ones passed in and allows passing of contextual validation validation information via 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. 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) 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) StructFilteredCtx

func (v *Validate) StructFilteredCtx(ctx context.Context, s any, 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 via context.Context

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

func (v *Validate) StructPartial(s any, fields ...string) error

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) StructPartialCtx

func (v *Validate) StructPartialCtx(ctx context.Context, s any, fields ...string) (err error)

StructPartialCtx validates the fields passed in only, ignoring all others and allows passing of contextual validation validation information via context.Context 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) ValidateMap

func (v *Validate) ValidateMap(data map[string]any, rules map[string]any) map[string]any

ValidateMap validates map data form a map of tags

func (Validate) ValidateMapCtx

func (v Validate) ValidateMapCtx(ctx context.Context, data map[string]any, rules map[string]any) map[string]any

ValidateMapCtx validates a map using a map of validation rules and allows passing of contextual validation validation information via context.Context.

func (*Validate) Var

func (v *Validate) Var(field any, tag string) error

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) VarCtx

func (v *Validate) VarCtx(ctx context.Context, field any, tag string) (err error)

VarCtx validates a single variable using tag style validation and allows passing of contextual validation validation information via context.Context. 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

func (v *Validate) VarWithValue(field any, other any, tag string) error

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

func (*Validate) VarWithValueCtx

func (v *Validate) VarWithValueCtx(ctx context.Context, field any, other any, 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 validation information via context.Context. 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

Directories

Path Synopsis
_examples

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL