package
1.0.26
Repository: https://github.com/askasoft/pango.git
Documentation: pkg.go.dev

# 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:

TagDescription
eqcsfieldField Equals Another Field (relative)
eqfieldField Equals Another Field
fieldcontainsNOT DOCUMENTED IN doc.go
fieldexcludesNOT DOCUMENTED IN doc.go
gtcsfieldField Greater Than Another Relative Field
gtecsfieldField Greater Than or Equal To Another Relative Field
gtefieldField Greater Than or Equal To Another Field
gtfieldField Greater Than Another Field
ltcsfieldLess Than Another Relative Field
ltecsfieldLess Than or Equal To Another Relative Field
ltefieldLess Than or Equal To Another Field
ltfieldLess Than Another Field
necsfieldField Does Not Equal Another Field (relative)
nefieldField Does Not Equal Another Field

Network:

TagDescription
cidrClassless Inter-Domain Routing CIDR
cidrv4Classless Inter-Domain Routing CIDRv4
cidrv6Classless Inter-Domain Routing CIDRv6
datauriData URL
fqdnFull Qualified Domain Name (FQDN)
hostnameHostname RFC 952
hostname_portHostPort
hostname_rfc1123Hostname RFC 1123
ipInternet Protocol Address IP
ip4_addrInternet Protocol Address IPv4
ip6_addrInternet Protocol Address IPv6
ip_addrInternet Protocol Address IP
ipv4Internet Protocol Address IPv4
ipv6Internet Protocol Address IPv6
macMedia Access Control Address MAC
tcp4_addrTransmission Control Protocol Address TCPv4
tcp6_addrTransmission Control Protocol Address TCPv6
tcp_addrTransmission Control Protocol Address TCP
udp4_addrUser Datagram Protocol Address UDPv4
udp6_addrUser Datagram Protocol Address UDPv6
udp_addrUser Datagram Protocol Address UDP
unix_addrUnix domain socket end point Address
uriURI String
urlURL String
httpurlURL (https?://) String
httpsurlURL (https://) String

Strings:

TagDescription
letterAscii Letter Only
letternumAscii Letter or Number
utfletterUnicode Letter
utfletternumUnicode Letter or Number
asciiASCII
booleanBoolean
containsContains
containsanyContains Any
containsruneContains Rune
endsnotwithEnds With
endswithEnds With
excludesExcludes
excludesallExcludes All
excludesruneExcludes Rune
lowercaseLowercase
multibyteMulti-Byte Characters
numberNOT DOCUMENTED IN doc.go
numericNumeric
decimalDecimal
printablePrintable Unicode
printasciiPrintable ASCII
startsnotwithStarts Not With
startswithStarts With
uppercaseUppercase

Format:

TagDescription
base64Base64 String
base64urlBase64URL String
bicBusiness Identifier Code (ISO 9362)
bcp47_language_tagLanguage tag (BCP 47)
btc_addrBitcoin Address
btc_addr_bech32Bitcoin Bech32 Address (segwit)
datetimeDatetime
durationDuration
e164e164 formatted phone number
emailE-mail String
eth_addrEthereum Address
hexadecimalHexadecimal String
hexcolorHexcolor String
hslHSL String
hslaHSLA String
htmlHTML Tags
html_encodedHTML Encoded
isbnInternational Standard Book Number
isbn10International Standard Book Number 10
isbn13International Standard Book Number 13
iso3166_1_alpha2Two-letter country code (ISO 3166-1 alpha-2)
iso3166_1_alpha3Three-letter country code (ISO 3166-1 alpha-3)
iso3166_1_alpha_numericNumeric country code (ISO 3166-1 numeric)
iso3166_2Country subdivision code (ISO 3166-2)
iso4217Currency code (ISO 4217)
jsonJSON
jwtJSON Web Token (JWT)
latitudeLatitude
longitudeLongitude
postcode_iso3166_alpha2Postcode
postcode_iso3166_alpha2_fieldPostcode
rgbRGB String
rgbaRGBA String
ssnSocial Security Number SSN
timezoneTimezone
uuidUniversally Unique Identifier UUID
uuid3Universally Unique Identifier UUID v3
uuid3_rfc4122Universally Unique Identifier UUID v3 RFC4122
uuid4Universally Unique Identifier UUID v4
uuid4_rfc4122Universally Unique Identifier UUID v4 RFC4122
uuid5Universally Unique Identifier UUID v5
uuid5_rfc4122Universally Unique Identifier UUID v5 RFC4122
uuid_rfc4122Universally Unique Identifier UUID RFC4122
semverSemantic Versioning 2.0.0
ulidUniversally Unique Lexicographically Sortable Identifier ULID

Comparisons:

TagDescription
eqEquals
neNot Equal
gtGreater than
gteGreater than or equal
minGreater than or equal
ltLess Than
lteLess Than or Equal
maxLess Than or Equal
btwBetween

Length:

TagDescription
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:

TagDescription
dirDirectory
fileFile path
isdefaultIs Default
oneofOne Of
requiredRequired
required_ifRequired If
required_unlessRequired Unless
required_withRequired With
required_with_allRequired With All
required_withoutRequired Without
required_without_allRequired Without All
excluded_withExcluded With
excluded_with_allExcluded With All
excluded_withoutExcluded Without
excluded_without_allExcluded Without All
uniqueUnique
regexpRegular Expression Match

Aliases:

TagDescription
iscolorhexcolor|rgb|rgba|hsl|hsla
alphaletter
alphanumletternum
alphaunicodeutfletter
alphanumunicodeutfletternum

# Functions

IsBase64 checks if a string is base64 encoded.
IsBase64URL checks if a string is base64 url safe encoded.
IsByteLength checks if the string's length (in bytes) falls in a range.
IsCIDR checks if a string is a valid v4 or v6 CIDR address.
IsCIDRv4 checks if a string is a valid v4 CIDR address.
IsCIDRv6 checks if a string is a valid v6 CIDR address.
IsCRC32 checks is a string is a CRC32 hash.
IsCRC32b checks is a string is a CRC32b hash.
IsCreditCard checks if the string is a credit card.
IsDataURI checks if a string is base64 encoded data URI such as an image.
IsDialString validates the given string for usage with the various Dial() functions.
IsDNSName will validate the given string as a DNS name.
IsEmail checks if the string is an email.
IsExistingEmail checks if the string is an email of existing domain.
IsFileName is illegal file name.
IsHash checks if a string is a hash of type algorithm.
IsHexColor checks if the string is a hex decimal color.
IsHost checks if the string is a valid IP (both v4 and v6) or a valid DNS name.
IsHSLAColor checks if the string is a valid HSLA color in form hsla(0, 100%, 50%, 0.5).
IsHSLColor checks if the string is a valid HSLA color in form hsl(0, 100%, 50%).
IsHttpsURL checks if the string is an https:// URL.
IsHttpURL checks if the string is an https?:// URL.
IsIMEI checks if a string is valid IMEI.
IsIMSI checks if a string is valid IMSI.
IsIP checks if a string is either IP version 4 or 6.
IsIP4AddrResolvable checks if the string is a resolvable ip v4 address.
IsIP6AddrResolvable checks if the string is a resolvable ip v6 address.
IsIPAddrResolvable checks if the string is a resolvable ip address.
IsIPv4 checks if the string is an IP version 4.
IsIPv6 checks if the string is an IP version 6.
IsISBN checks if the string is an ISBN (version 10 or 13).
IsISBN10 checks if the string is an ISBN version 10.
IsISBN13 checks if the string is an ISBN version 13.
IsJSON checks if the string is valid JSON (note: uses json.Unmarshal).
IsJWT checks if the string is a valid JWT string.
IsLatitude checks if a string is valid latitude.
IsLongitude checks if a string is valid longitude.
IsMAC checks if a string is valid MAC address.
IsMagnetURI checks if a string is valid magnet URI.
IsMD4 checks is a string is a MD4 hash.
IsMD5 checks is a string is a MD5 hash.
IsPort checks if a string represents a valid port.
IsRequestURI checks if the string rawurl, assuming it was received in an HTTP request, is an absolute URI or an absolute path.
IsRequestURL checks if the string rawurl, assuming it was received in an HTTP request, is a valid URL confirm to RFC 3986.
IsRGBAColor checks if the string is a valid RGBA color in form rgb(RRR, GGG, BBB).
IsRGBColor checks if the string is a valid RGB color in form rgb(RRR, GGG, BBB).
IsRipeMD128 checks is a string is a RipeMD128 hash.
IsRipeMD160 checks is a string is a RipeMD160 hash.
IsSHA1 checks is a string is a SHA-1 hash.
IsSHA256 checks is a string is a SHA256 hash.
IsSHA384 checks is a string is a SHA384 hash.
IsSHA512 checks is a string is a SHA512 hash.
IsSSN checks if the string is a valid SSN string.
IsSwiftCode checks if the string is a valid Business Identifier Code (SWIFT code), defined in ISO 9362.
IsTiger128 checks is a string is a Tiger128 hash.
IsTiger160 checks is a string is a Tiger160 hash.
IsTiger192 checks is a string is a Tiger192 hash.
IsURI checks if the string is an URI.
IsURL checks if the string is an URL.
IsUUID checks if the string is a UUID (version 3, 4 or 5).
IsUUIDv3 checks if the string is a UUID version 3.
IsUUIDv4 checks if the string is a UUID version 4.
IsUUIDv5 checks if the string is a UUID version 5.
New returns a new instance of 'validate' with sane defaults.

# Structs

InvalidValidationError describes an invalid argument passed to `Struct`, `StructExcept`, StructPartial` or `Field`.
Validate contains the validator settings and cache.

# Interfaces

FieldError contains all functions to get error details.
FieldLevel contains all the information and helper functions to validate a field.
StructLevel contains all the information and helper functions to validate a struct.

# Type aliases

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.
FilterFunc is the type used to filter fields using StructFiltered(...) function.
Func accepts a FieldLevel interface for all validation needs.
FuncCtx accepts a context.Context and FieldLevel interface for all validation needs.
StructLevelFunc accepts all values needed for struct level validation.
StructLevelFuncCtx accepts all values needed for struct level validation but also allows passing of contextual validation information via context.Context.
TagNameFunc allows for adding of a custom tag name parser.
ValidationErrors is an array of FieldError's for use in custom error messages post validation.