# 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 |
---|---|
letter | Ascii Letter Only |
letternum | Ascii Letter or Number |
utfletter | Unicode Letter |
utfletternum | Unicode Letter or Number |
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 |
printable | Printable Unicode |
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 |
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 |
alpha | letter |
alphanum | letternum |
alphaunicode | utfletter |
alphanumunicode | utfletternum |
# 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.