import "github.com/asaskevich/govalidator"
Package govalidator is package of validators and sanitizers for strings, structs and collections.
arrays.go converter.go doc.go error.go numerics.go patterns.go types.go utils.go validator.go
const ( Email string = "" /* 1210 byte string literal not displayed */ CreditCard string = "" /* 233 byte string literal not displayed */ ISBN10 string = "^(?:[0-9]{9}X|[0-9]{10})$" ISBN13 string = "^(?:[0-9]{13})$" UUID3 string = "^[0-9a-f]{8}-[0-9a-f]{4}-3[0-9a-f]{3}-[0-9a-f]{4}-[0-9a-f]{12}$" UUID4 string = "^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$" UUID5 string = "^[0-9a-f]{8}-[0-9a-f]{4}-5[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$" UUID string = "^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" Alpha string = "^[a-zA-Z]+$" Alphanumeric string = "^[a-zA-Z0-9]+$" Numeric string = "^[0-9]+$" Int string = "^(?:[-+]?(?:0|[1-9][0-9]*))$" Float string = "^(?:[-+]?(?:[0-9]+))?(?:\\.[0-9]*)?(?:[eE][\\+\\-]?(?:[0-9]+))?$" Hexadecimal string = "^[0-9a-fA-F]+$" Hexcolor string = "^#?([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$" RGBcolor string = "" /* 159 byte string literal not displayed */ ASCII string = "^[\x00-\x7F]+$" Multibyte string = "[^\x00-\x7F]" FullWidth string = "[^\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]" HalfWidth string = "[\u0020-\u007E\uFF61-\uFF9F\uFFA0-\uFFDC\uFFE8-\uFFEE0-9a-zA-Z]" Base64 string = "^(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\\/]{3}=|[A-Za-z0-9+\\/]{4})$" PrintableASCII string = "^[\x20-\x7E]+$" DataURI string = "^data:.+\\/(.+);base64$" MagnetURI string = "^magnet:\\?xt=urn:[a-zA-Z0-9]+:[a-zA-Z0-9]{32,40}&dn=.+&tr=.+$" Latitude string = "^[-+]?([1-8]?\\d(\\.\\d+)?|90(\\.0+)?)$" Longitude string = "^[-+]?(180(\\.0+)?|((1[0-7]\\d)|([1-9]?\\d))(\\.\\d+)?)$" DNSName string = `^([a-zA-Z0-9_]{1}[a-zA-Z0-9_-]{0,62}){1}(\.[a-zA-Z0-9_]{1}[a-zA-Z0-9_-]{0,62})*[\._]?$` IP string = "" /* 661 byte string literal not displayed */ URLSchema string = `((ftp|tcp|udp|wss?|https?):\/\/)` URLUsername string = `(\S+(:\S*)?@)` URLPath string = `((\/|\?|#)[^\s]*)` URLPort string = `(:(\d{1,5}))` URLIP string = `([1-9]\d?|1\d\d|2[01]\d|22[0-3]|24\d|25[0-5])(\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])){2}(?:\.([0-9]\d?|1\d\d|2[0-4]\d|25[0-5]))` URLSubdomain string = `((www\.)|([a-zA-Z0-9]+([-_\.]?[a-zA-Z0-9])*[a-zA-Z0-9]\.[a-zA-Z0-9]+))` URL = `^` + URLSchema + `?` + URLUsername + `?` + `((` + URLIP + `|(\[` + IP + `\])|(([a-zA-Z0-9]([a-zA-Z0-9-_]+)?[a-zA-Z0-9]([-\.][a-zA-Z0-9]+)*)|(` + URLSubdomain + `?))?(([a-zA-Z\x{00a1}-\x{ffff}0-9]+-?-?)*[a-zA-Z\x{00a1}-\x{ffff}0-9]+)(?:\.([a-zA-Z\x{00a1}-\x{ffff}]{1,}))?))\.?` + URLPort + `?` + URLPath + `?$` SSN string = `^\d{3}[- ]?\d{2}[- ]?\d{4}$` WinPath string = `^[a-zA-Z]:\\(?:[^\\/:*?"<>|\r\n]+\\)*[^\\/:*?"<>|\r\n]*$` UnixPath string = `^(/[^/\x00]*)+/?$` Semver string = "" /* 185 byte string literal not displayed */ IMEI string = "^[0-9a-f]{14}$|^\\d{15}$|^\\d{18}$" IMSI string = "^\\d{14,15}$" )
Basic regular expressions for validating strings
const ( // Unknown is unresolved OS type Unknown = iota // Win is Windows type Win // Unix is *nix OS types Unix )
Used by IsFilePath func
var CustomTypeTagMap = &customTypeTagMap{validators: make(map[string]CustomTypeValidator)}
CustomTypeTagMap is a map of functions that can be used as tags for ValidateStruct function. Use this to validate compound or custom types that need to be handled as a whole, e.g. `type UUID [16]byte` (this would be handled as an array of bytes).
var Escape = html.EscapeString
Escape replaces <, >, & and " with HTML entities.
var ISO3166List = []ISO3166Entry{ /* 249 elements not displayed */ }
ISO3166List based on https://www.iso.org/obp/ui/#search/code/ Code Type "Officially Assigned Codes"
ISO4217List is the list of ISO currency codes
var ISO693List = []ISO693Entry{ /* 184 elements not displayed */ }
ISO693List based on http://data.okfn.org/data/core/language-codes/r/language-codes-3b2.json
var InterfaceParamTagMap = map[string]InterfaceParamValidator{ "type": IsType, }
InterfaceParamTagMap is a map of functions accept variants parameters for an interface value
var InterfaceParamTagRegexMap = map[string]*regexp.Regexp{ "type": regexp.MustCompile(`^type\((.*)\)$`), }
InterfaceParamTagRegexMap maps interface param tags to their respective regexes.
var ParamTagMap = map[string]ParamValidator{ "length": ByteLength, "range": Range, "runelength": RuneLength, "stringlength": StringLength, "matches": StringMatches, "in": IsInRaw, "rsapub": IsRsaPub, "minstringlength": MinStringLength, "maxstringlength": MaxStringLength, }
ParamTagMap is a map of functions accept variants parameters
var ParamTagRegexMap = map[string]*regexp.Regexp{ "range": regexp.MustCompile("^range\\((\\d+)\\|(\\d+)\\)$"), "length": regexp.MustCompile("^length\\((\\d+)\\|(\\d+)\\)$"), "runelength": regexp.MustCompile("^runelength\\((\\d+)\\|(\\d+)\\)$"), "stringlength": regexp.MustCompile("^stringlength\\((\\d+)\\|(\\d+)\\)$"), "in": regexp.MustCompile(`^in\((.*)\)`), "matches": regexp.MustCompile(`^matches\((.+)\)$`), "rsapub": regexp.MustCompile("^rsapub\\((\\d+)\\)$"), "minstringlength": regexp.MustCompile("^minstringlength\\((\\d+)\\)$"), "maxstringlength": regexp.MustCompile("^maxstringlength\\((\\d+)\\)$"), }
ParamTagRegexMap maps param tags to their respective regexes.
var TagMap = map[string]Validator{ "email": IsEmail, "url": IsURL, "dialstring": IsDialString, "requrl": IsRequestURL, "requri": IsRequestURI, "alpha": IsAlpha, "utfletter": IsUTFLetter, "alphanum": IsAlphanumeric, "utfletternum": IsUTFLetterNumeric, "numeric": IsNumeric, "utfnumeric": IsUTFNumeric, "utfdigit": IsUTFDigit, "hexadecimal": IsHexadecimal, "hexcolor": IsHexcolor, "rgbcolor": IsRGBcolor, "lowercase": IsLowerCase, "uppercase": IsUpperCase, "int": IsInt, "float": IsFloat, "null": IsNull, "notnull": IsNotNull, "uuid": IsUUID, "uuidv3": IsUUIDv3, "uuidv4": IsUUIDv4, "uuidv5": IsUUIDv5, "creditcard": IsCreditCard, "isbn10": IsISBN10, "isbn13": IsISBN13, "json": IsJSON, "multibyte": IsMultibyte, "ascii": IsASCII, "printableascii": IsPrintableASCII, "fullwidth": IsFullWidth, "halfwidth": IsHalfWidth, "variablewidth": IsVariableWidth, "base64": IsBase64, "datauri": IsDataURI, "ip": IsIP, "port": IsPort, "ipv4": IsIPv4, "ipv6": IsIPv6, "dns": IsDNSName, "host": IsHost, "mac": IsMAC, "latitude": IsLatitude, "longitude": IsLongitude, "ssn": IsSSN, "semver": IsSemver, "rfc3339": IsRFC3339, "rfc3339WithoutZone": IsRFC3339WithoutZone, "ISO3166Alpha2": IsISO3166Alpha2, "ISO3166Alpha3": IsISO3166Alpha3, "ISO4217": IsISO4217, "IMEI": IsIMEI, }
TagMap is a map of functions, that can be used as tags for ValidateStruct function.
Abs returns absolute value of number
Code:
_ = Abs(-123.3e1) // 123.3e1 _ = Abs(+0) // 0 _ = Abs(321) // 321
BlackList removes characters that appear in the blacklist.
ByteLength checks string's length
CamelCaseToUnderscore converts from camel case form to underscore separated form. Ex.: MyFunc => my_func
Contains checks if the string contains the substring.
func Count(array []interface{}, iterator ConditionIterator) int
Count iterates over the slice and apply ConditionIterator to every item. Returns count of items that meets ConditionIterator.
Code:
data := []interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
var fn ConditionIterator = func(value interface{}, index int) bool {
return value.(int)%2 == 0
}
_ = Count(data, fn) // result = 5
Each iterates over the slice and apply Iterator to every item
Code:
data := []interface{}{1, 2, 3, 4, 5} var fn Iterator = func(value interface{}, index int) { println(value.(int)) } Each(data, fn)
ErrorByField returns error for specified field of the struct validated by ValidateStruct or empty string if there are no errors or this field doesn't exists or doesn't have any errors.
ErrorsByField returns map of errors of the struct validated by ValidateStruct or empty map if there are no errors.
func Every(array []interface{}, iterator ConditionIterator) bool
Every validates that every item of array corresponds to ConditionIterator. Returns boolean.
func Filter(array []interface{}, iterator ConditionIterator) []interface{}
Filter iterates over the slice and apply ConditionIterator to every item. Returns new slice.
Code:
data := []interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
var fn ConditionIterator = func(value interface{}, index int) bool {
return value.(int)%2 == 0
}
_ = Filter(data, fn) // result = []interface{}{2, 4, 6, 8, 10}
func Find(array []interface{}, iterator ConditionIterator) interface{}
Find iterates over the slice and apply ConditionIterator to every item. Returns first item that meet ConditionIterator or nil otherwise.
Code:
data := []interface{}{1, 2, 3, 4, 5}
var fn ConditionIterator = func(value interface{}, index int) bool {
return value.(int) == 4
}
_ = Find(data, fn) // result = 4
GetLine returns specified line of multiline string
GetLines splits string by "\n" and return array of lines
HasLowerCase checks if the string contains at least 1 lowercase. Empty string is valid.
HasUpperCase checks if the string contains as least 1 uppercase. Empty string is valid.
HasWhitespace checks if the string contains any whitespace
HasWhitespaceOnly checks the string only contains whitespace
InRange returns true if value lies between left and right border, generic type to handle int, float32, float64 and string. All types must the same type. False if value doesn't lie in range or if it incompatible or not comparable
Code:
_ = InRange(10, 11, 20) // false _ = InRange(10.02, -10.124, 10.234) // true _ = InRange("abc", "a", "cba") // true
InRangeFloat32 returns true if value lies between left and right border
Code:
_ = InRangeFloat32(10.02, -10.124, 10.234) // true _ = InRangeFloat32(10.123, 10.123, 20.431) // true _ = InRangeFloat32(10.235, 11.124, 20.235) // false
InRangeFloat64 returns true if value lies between left and right border
Code:
_ = InRangeFloat64(10.02, -10.124, 10.234) // true _ = InRangeFloat64(10.123, 10.123, 20.431) // true _ = InRangeFloat64(10.235, 11.124, 20.235) // false
InRangeInt returns true if value lies between left and right border
Code:
_ = InRangeInt(10, -10, 10) // true _ = InRangeInt(10, 10, 20) // true _ = InRangeInt(10, 11, 20) // false
IsASCII checks if the string contains ASCII chars only. Empty string is valid.
IsAlpha checks if the string contains only letters (a-zA-Z). Empty string is valid.
IsAlphanumeric checks if the string contains only letters and numbers. Empty string is valid.
IsBase64 checks if a string is base64 encoded.
IsByteLength checks if the string's length (in bytes) falls in a range.
IsCIDR checks if the string is an valid CIDR notiation (IPV4 & IPV6)
IsCRC32 checks is a string is a CRC32 hash. Alias for `IsHash(str, "crc32")`
IsCRC32b checks is a string is a CRC32b hash. Alias for `IsHash(str, "crc32b")`
IsCreditCard checks if the string is a credit card.
IsDNSName will validate the given string as a DNS name
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
IsDivisibleBy checks if the string is a number that's divisible by another. If second argument is not valid integer or zero, it's return false. Otherwise, if first argument is not valid integer or zero, it's return true (Invalid string converts to zero).
This small example illustrate how to work with IsDivisibleBy function.
Code:
println("1024 is divisible by 64: ", IsDivisibleBy("1024", "64"))
IsEmail checks if the string is an email.
IsExistingEmail checks if the string is an email of existing domain
IsFilePath checks is a string is Win or Unix file path and returns it's type.
IsFloat checks if the string is a float.
IsFullWidth checks if the string contains any full-width chars. Empty string is valid.
IsHalfWidth checks if the string contains any half-width chars. Empty string is valid.
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']
IsHexadecimal checks if the string is a hexadecimal number.
IsHexcolor checks if the string is a hexadecimal color.
IsHost checks if the string is a valid IP (both v4 and v6) or a valid DNS name
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. Alias for `net.ParseIP`
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). If version value is not equal to 10 or 13, it will be checks both variants.
IsISBN10 checks if the string is an ISBN version 10.
IsISBN13 checks if the string is an ISBN version 13.
IsISO3166Alpha2 checks if a string is valid two-letter country code
IsISO3166Alpha3 checks if a string is valid three-letter country code
IsISO4217 checks if string is valid ISO currency code
IsISO693Alpha2 checks if a string is valid two-letter language code
IsISO693Alpha3b checks if a string is valid three-letter language code
IsIn checks if string str is a member of the set of strings params
IsInRaw checks if string is in list of allowed values
IsInt checks if the string is an integer. Empty string is valid.
IsJSON checks if the string is valid JSON (note: uses json.Unmarshal).
IsLatitude checks if a string is valid latitude.
IsLongitude checks if a string is valid longitude.
IsLowerCase checks if the string is lowercase. Empty string is valid.
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
IsMD4 checks is a string is a MD4 hash. Alias for `IsHash(str, "md4")`
IsMD5 checks is a string is a MD5 hash. Alias for `IsHash(str, "md5")`
IsMagnetURI checks if a string is valid magnet URI
IsMongoID checks if the string is a valid hex-encoded representation of a MongoDB ObjectId.
IsMultibyte checks if the string contains one or more multibyte chars. Empty string is valid.
IsNatural returns true if value is natural number (positive and whole)
Code:
_ = IsNatural(1.123) // false _ = IsNatural(1.0) // true _ = IsNatural(-10) // false
IsNegative returns true if value < 0
Code:
_ = IsNegative(-123) // true _ = IsNegative(0) // false _ = IsNegative(123) // false
IsNonNegative returns true if value >= 0
Code:
_ = IsNonNegative(-123) // false _ = IsNonNegative(0) // true _ = IsNonNegative(123) // true
IsNonPositive returns true if value <= 0
Code:
_ = IsNonPositive(-123) // true _ = IsNonPositive(0) // true _ = IsNonPositive(123) // false
IsNotNull checks if the string is not null.
IsNull checks if the string is null.
IsNumeric checks if the string contains only numbers. Empty string is valid.
IsPort checks if a string represents a valid port
IsPositive returns true if value > 0
Code:
_ = IsPositive(-123) // false _ = IsPositive(0) // false _ = IsPositive(123) // true
IsPrintableASCII checks if the string contains printable ASCII chars only. Empty string is valid.
IsRFC3339 checks if string is valid timestamp value according to RFC3339
IsRFC3339WithoutZone checks if string is valid timestamp value according to RFC3339 which excludes the timezone.
IsRGBcolor checks if the string is a valid RGB color in form rgb(RRR, GGG, BBB).
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
IsRipeMD128 checks is a string is a RipeMD128 hash. Alias for `IsHash(str, "ripemd128")`
IsRipeMD160 checks is a string is a RipeMD160 hash. Alias for `IsHash(str, "ripemd160")`
IsRsaPub checks whether string is valid RSA key Alias for IsRsaPublicKey
IsRsaPublicKey checks if a string is valid public key with provided length
IsSHA1 checks is a string is a SHA-1 hash. Alias for `IsHash(str, "sha1")`
IsSHA256 checks is a string is a SHA256 hash. Alias for `IsHash(str, "sha256")`
IsSHA384 checks is a string is a SHA384 hash. Alias for `IsHash(str, "sha384")`
IsSHA512 checks is a string is a SHA512 hash. Alias for `IsHash(str, "sha512")`
IsSSN will validate the given string as a U.S. Social Security Number
IsSemver checks if string is valid semantic version
IsTiger128 checks is a string is a Tiger128 hash. Alias for `IsHash(str, "tiger128")`
IsTiger160 checks is a string is a Tiger160 hash. Alias for `IsHash(str, "tiger160")`
IsTiger192 checks is a string is a Tiger192 hash. Alias for `IsHash(str, "tiger192")`
IsTime checks if string is valid according to given format
IsType checks if interface is of some type
IsURL checks if the string is an URL.
IsUTFDigit checks if the string contains only unicode radix-10 decimal digits. Empty string is valid.
IsUTFLetter checks if the string contains only unicode letter characters. Similar to IsAlpha but for all languages. Empty string is valid.
IsUTFLetterNumeric checks if the string contains only unicode letters and numbers. Empty string is valid.
IsUTFNumeric checks if the string contains only unicode numbers of any kind. Numbers can be 0-9 but also Fractions ¾,Roman Ⅸ and Hangzhou 〩. Empty string is valid.
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.
IsUnixTime checks if string is valid unix timestamp value
IsUpperCase checks if the string is uppercase. Empty string is valid.
IsVariableWidth checks if the string contains a mixture of full and half-width chars. Empty string is valid.
IsWhole returns true if value is whole number
Code:
_ = IsWhole(1.123) // false _ = IsWhole(1.0) // true _ = IsWhole(10) // true
LeftTrim trims characters from the left side of the input. If second argument is empty, it will remove leading spaces.
func Map(array []interface{}, iterator ResultIterator) []interface{}
Map iterates over the slice and apply ResultIterator to every item. Returns new slice as a result.
Code:
data := []interface{}{1, 2, 3, 4, 5}
var fn ResultIterator = func(value interface{}, index int) interface{} {
return value.(int) * 3
}
_ = Map(data, fn) // result = []interface{}{1, 6, 9, 12, 15}
Matches checks if string matches the pattern (pattern is regular expression) In case of error return false
MaxStringLength checks string's maximum length (including multi byte strings)
MinStringLength checks string's minimum length (including multi byte strings)
NormalizeEmail canonicalize an email address. The local part of the email address is lowercased for all domains; the hostname is always lowercased and the local part of the email address is always lowercased for hosts that are known to be case-insensitive (currently only GMail). Normalization follows special rules for known providers: currently, GMail addresses have dots removed in the local part and are stripped of tags (e.g. some.one+tag@gmail.com becomes someone@gmail.com) and all @googlemail.com addresses are normalized to @gmail.com.
PadBoth pads both sides of a string if size of string is less then indicated pad length
PadLeft pads left side of a string if size of string is less then indicated pad length
PadRight pads right side of a string if size of string is less then indicated pad length
Range checks string's length
func Reduce(array []interface{}, iterator ReduceIterator, initialValue interface{}) interface{}
Reduce boils down a list of values into a single value by ReduceIterator
RemoveTags removes all tags from HTML string
ReplacePattern replaces regular expression pattern in string
Code:
// Replace in "http123123ftp://git534543hub.comio" following (pattern "(ftp|io|[0-9]+)"):
// - Sequence "ftp".
// - Sequence "io".
// - Sequence of digits.
// with empty string.
println(ReplacePattern("http123123ftp://git534543hub.comio", "(ftp|io|[0-9]+)", "") == "http://github.com")
Reverse returns reversed string
RightTrim trims characters from the right side of the input. If second argument is empty, it will remove trailing spaces.
RuneLength checks string's length Alias for StringLength
SafeFileName returns safe string that can be used in file names
SetFieldsRequiredByDefault causes validation to fail when struct fields do not include validations or are not explicitly marked as exempt (using `valid:"-"` or `valid:"email,optional"`). This struct definition will fail govalidator.ValidateStruct() (and the field values do not matter):
type exampleStruct struct { Name string `` Email string `valid:"email"`
This, however, will only fail when Email is empty or an invalid email address:
type exampleStruct2 struct { Name string `valid:"-"` Email string `valid:"email"`
Lastly, this will only fail when Email is an invalid email address but not when it's empty:
type exampleStruct2 struct { Name string `valid:"-"` Email string `valid:"email,optional"`
SetNilPtrAllowedByRequired causes validation to pass for nil ptrs when a field is set to required. The validation will still reject ptr fields in their zero value state. Example with this enabled:
type exampleStruct struct { Name *string `valid:"required"`
With `Name` set to "", this will be considered invalid input and will cause a validation error. With `Name` set to nil, this will be considered valid by validation. By default this is disabled.
Sign returns signum of number: 1 in case of value > 0, -1 in case of value < 0, 0 otherwise
Code:
_ = Sign(-123) // -1 _ = Sign(123) // 1 _ = Sign(0) // 0
func Some(array []interface{}, iterator ConditionIterator) bool
Some validates that any item of array corresponds to ConditionIterator. Returns boolean.
StringLength checks string's length (including multi byte strings)
StringMatches checks if a string matches a given pattern.
StripLow removes characters with a numerical value < 32 and 127, mostly control characters. If keep_new_lines is true, newline characters are preserved (\n and \r, hex 0xA and 0xD).
ToBoolean convert the input string to a boolean.
Code:
// Returns the boolean value represented by the string. // It accepts 1, t, T, TRUE, true, True, 0, f, F, FALSE, false, False. // Any other value returns an error. _, _ = ToBoolean("false") // false, nil _, _ = ToBoolean("T") // true, nil _, _ = ToBoolean("123123") // false, error
ToFloat convert the input string to a float, or 0.0 if the input is not a float.
Code:
_, _ = ToFloat("-124.2e123") // -124.2e123, nil _, _ = ToFloat("false") // 0, error
ToInt convert the input string or any int type to an integer type 64, or 0 if the input is not an integer.
Code:
_, _ = ToInt(1.0) // 1, nil _, _ = ToInt("-124") // -124, nil _, _ = ToInt("false") // 0, error
ToJSON convert the input to a valid JSON string
Code:
_, _ = ToJSON([]int{1, 2, 3}) // [1, 2, 3] _, _ = ToJSON(map[int]int{1: 2, 2: 3}) // { "1": 2, "2": 3 } _, _ = ToJSON(func() {}) // error
ToString convert the input to a string.
Code:
_ = ToString(new(interface{})) // 0xc000090200 _ = ToString(time.Second + time.Hour) // 1h1s _ = ToString(123) // 123
Trim trims characters from both sides of the input. If second argument is empty, it will remove spaces.
Code:
// Remove from left and right spaces and "\r", "\n", "\t" characters println(Trim(" \r\r\ntext\r \t\n", "") == "text") // Remove from left and right characters that are between "1" and "8". // "1-8" is like full list "12345678". println(Trim("1234567890987654321", "1-8") == "909")
Truncate a string to the closest length without breaking words.
TruncatingErrorf removes extra args from fmt.Errorf if not formatted in the str object
UnderscoreToCamelCase converts from underscore separated form to camel case form. Ex.: my_func => MyFunc
func ValidateArray(array []interface{}, iterator ConditionIterator) bool
ValidateArray performs validation according to condition iterator that validates every element of the array
ValidateMap use validation map for fields. result will be equal to `false` if there are any errors. s is the map containing the data to be validated. m is the validation map in the form:
map[string]interface{}{"name":"required,alpha","address":map[string]interface{}{"line1":"required,alphanum"}}
func ValidateMapAsync(s map[string]interface{}, m map[string]interface{}) (<-chan bool, <-chan error)
ValidateMapAsync performs async validation of the map and returns results through the channels
ValidateStruct use tags for fields. result will be equal to `false` if there are any errors. todo currently there is no guarantee that errors will be returned in predictable order (tests may to fail)
Code:
type Post struct {
Title string `valid:"alphanum,required"`
Message string `valid:"duck,ascii"`
AuthorIP string `valid:"ipv4"`
}
post := &Post{"My Example Post", "duck", "123.234.54.3"}
//Add your own struct validation tags
TagMap["duck"] = Validator(func(str string) bool {
return str == "duck"
})
result, err := ValidateStruct(post)
if err != nil {
println("error: " + err.Error())
}
println(result)
ValidateStructAsync performs async validation of the struct and returns results through the channels
WhiteList removes characters that do not appear in the whitelist.
Code:
// Remove all characters from string ignoring characters between "a" and "z"
println(WhiteList("a3a43a5a4a3a2a23a4a5a4a3a4", "a-z") == "aaaaaaaaaaaa")
ConditionIterator is the function that accepts element of slice/array and its index and returns boolean
CustomTypeValidator is a wrapper for validator functions that returns bool and accepts any type. The second parameter should be the context (in the case of validating a struct: the whole object being validated).
type Error struct { Name string Err error CustomErrorMessageExists bool // Validator indicates the name of the validator that failed Validator string Path []string }
Error encapsulates a name, an error and whether there's a custom error message or not.
Errors is an array of multiple errors and conforms to the error interface.
Errors returns itself.
type ISO3166Entry struct { EnglishShortName string FrenchShortName string Alpha2Code string Alpha3Code string Numeric string }
ISO3166Entry stores country codes
ISO693Entry stores ISO language codes
InterfaceParamValidator is a wrapper for functions that accept variants parameters for an interface value
Iterator is the function that accepts element of slice/array and its index
ParamValidator is a wrapper for validator functions that accept additional parameters.
type ReduceIterator func(interface{}, interface{}) interface{}
ReduceIterator is the function that accepts two element of slice/array and returns result of merging those values
ResultIterator is the function that accepts element of slice/array and its index and returns any result
UnsupportedTypeError is a wrapper for reflect.Type
func (e *UnsupportedTypeError) Error() string
Error returns string equivalent for reflect.Type
Validator is a wrapper for a validator function that returns bool and accepts string.
Package govalidator imports 23 packages (graph) and is imported by 900 packages. Updated 2020-12-21. Refresh now. Tools for package owners.