Documentation ¶
Overview ¶
Package govalidator is package of validators and sanitizers for strings, structs and collections.
Index ¶
- Constants
- Variables
- func Abs[V constraints.Integer | constraints.Float](value V) V
- func BlackList[T ~string](str, chars T) string
- func ByteLength[T ~string](str T, params ...T) bool
- func CamelCaseToUnderscore[T ~string](str T) string
- func Contains[T ~string](str, substring T) bool
- func Count[T any](array []T, iterator ConditionIterator[T]) int
- func Each[T any](array []T, iterator Iterator[T])
- func ErrorByField(e error, field string) string
- func ErrorsByField(e error) map[string]string
- func Every[T any](array []T, iterator ConditionIterator[T]) bool
- func Filter[T any](array []T, iterator ConditionIterator[T]) []T
- func Find[T any](array []T, iterator ConditionIterator[T]) (t T)
- func GetLine[T ~string](s T, index int) (string, error)
- func GetLines[T ~string](s T) []string
- func HasLowerCase[T ~string](str string) bool
- func HasUpperCase[T ~string](str string) bool
- func HasWhitespace[T ~string](str T) bool
- func HasWhitespaceOnly[T ~string](str T) bool
- func InRange[V constraints.Ordered](value V, left V, right V) bool
- func IsASCII[T ~string](str T) bool
- func IsAlpha[T ~string](str T) bool
- func IsAlphanumeric[T ~string](str T) bool
- func IsBase64[T ~string](str T) bool
- func IsByteLength[T ~string](str T, min, max int) bool
- func IsCIDR[T ~string](str T) bool
- func IsCRC32[T ~string](str T) bool
- func IsCRC32b[T ~string](str T) bool
- func IsCreditCard[T ~string](str T) bool
- func IsDNSName[T ~string](str T) bool
- func IsDataURI[T ~string](str T) bool
- func IsDialString[T ~string](str T) bool
- func IsDivisibleBy[T ~string](str, num T) bool
- func IsE164[T ~string](str T) bool
- func IsEmail[T ~string](str T) bool
- func IsExistingEmail[T ~string](email T) bool
- func IsFilePath[T ~string](str T) (bool, int)
- func IsFloat[T ~string](str string) bool
- func IsFullWidth[T ~string](str T) bool
- func IsHalfWidth[T ~string](str T) bool
- func IsHash[T ~string](str T, algorithm T) bool
- func IsHexadecimal[T ~string](str T) bool
- func IsHexcolor[T ~string](str string) bool
- func IsHost[T ~string](str T) bool
- func IsIMEI[T ~string](str T) bool
- func IsIMSI[T ~string](str T) bool
- func IsIP[T ~string](str T) bool
- func IsIPv4[T ~string](str T) bool
- func IsIPv6[T ~string](str T) bool
- func IsISBN[T ~string](str T, version int) bool
- func IsISBN10[T ~string](str T) bool
- func IsISBN13[T ~string](str T) bool
- func IsISO3166Alpha2[T ~string](str T) bool
- func IsISO3166Alpha3[T ~string](str T) bool
- func IsISO4217[T ~string](str T) bool
- func IsISO693Alpha2[T ~string](str T) bool
- func IsISO693Alpha3b[T ~string](str T) bool
- func IsIn[T ~string](str T, params ...string) bool
- func IsInRaw[T ~string](str T, params ...T) bool
- func IsInt[T ~string](str string) bool
- func IsJSON[T ~string](str T) bool
- func IsLatitude[T ~string](str T) bool
- func IsLongitude[T ~string](str T) bool
- func IsLowerCase[T ~string](str string) bool
- func IsMAC[T ~string](str T) bool
- func IsMD4[T ~string](str T) bool
- func IsMD5[T ~string](str T) bool
- func IsMagnetURI[T ~string](str T) bool
- func IsMongoID[T ~string](str T) bool
- func IsMultibyte[T ~string](str T) bool
- func IsNatural[V constraints.Integer | constraints.Float](value V) bool
- func IsNegative[V constraints.Integer | constraints.Float](value V) bool
- func IsNonNegative[V constraints.Integer | constraints.Float](value V) bool
- func IsNonPositive[V constraints.Integer | constraints.Float](value V) bool
- func IsNotNull[T ~string](str T) bool
- func IsNull[T ~string](str T) bool
- func IsNumeric[T ~string](str T) bool
- func IsPort[T ~string](str T) bool
- func IsPositive[V constraints.Integer | constraints.Float](value V) bool
- func IsPrintableASCII[T ~string](str T) bool
- func IsRFC3339[T ~string](str T) bool
- func IsRFC3339WithoutZone[T ~string](str T) bool
- func IsRGBcolor[T ~string](str string) bool
- func IsRegex[T ~string](str T) bool
- func IsRequestURI[T ~string](rawurl T) bool
- func IsRequestURL[T ~string](rawurl T) bool
- func IsRipeMD128[T ~string](str T) bool
- func IsRipeMD160[T ~string](str T) bool
- func IsRsaPub[T ~string](str T, params ...string) bool
- func IsRsaPublicKey[T ~string](str T, keylen int) bool
- func IsSHA1[T ~string](str T) bool
- func IsSHA256[T ~string](str T) bool
- func IsSHA3224[T ~string](str T) bool
- func IsSHA3256[T ~string](str T) bool
- func IsSHA3384[T ~string](str T) bool
- func IsSHA3512[T ~string](str T) bool
- func IsSHA384[T ~string](str T) bool
- func IsSHA512[T ~string](str T) bool
- func IsSSN[T ~string](str T) bool
- func IsSemver[T ~string](str T) bool
- func IsTiger128[T ~string](str T) bool
- func IsTiger160[T ~string](str T) bool
- func IsTiger192[T ~string](str T) bool
- func IsTime[T ~string](str T, format T) bool
- func IsType[T any](v T, params ...string) bool
- func IsULID[T ~string](str T) bool
- func IsURL[T ~string](s T) bool
- func IsUTFDigit[T ~string](s T) bool
- func IsUTFLetter[T ~string](str T) bool
- func IsUTFLetterNumeric[T ~string](str T) bool
- func IsUTFNumeric[T ~string](s T) bool
- func IsUUID[T ~string](str T) bool
- func IsUUIDv3[T ~string](str T) bool
- func IsUUIDv4[T ~string](str T) bool
- func IsUUIDv5[T ~string](str T) bool
- func IsUnixFilePath[T ~string](str T) bool
- func IsUnixTime[T ~string](str T) bool
- func IsUpperCase[T ~string](str string) bool
- func IsVariableWidth[T ~string](str T) bool
- func IsWhole[V constraints.Integer | constraints.Float](value V) bool
- func IsWinFilePath[T ~string](str T) bool
- func LeftTrim[T ~string](str, chars T) string
- func Map[T any](array []T, iterator ResultIterator[T]) []T
- func Matches[T ~string](str, pattern T) bool
- func MaxStringLength[T ~string](str T, params ...T) bool
- func MinStringLength[T ~string](str T, params ...T) bool
- func NormalizeEmail[T ~string](str T) (string, error)
- func PadBoth[T ~string](str T, padStr T, padLen int) T
- func PadLeft[T ~string](str T, padStr T, padLen int) T
- func PadRight[T ~string](str T, padStr T, padLen int) T
- func Range[T ~string](str T, params ...T) bool
- func Reduce[T any](array []T, iterator ReduceIterator[T], initialValue T) T
- func RemoveTags[T ~string](s T) string
- func ReplacePattern[T ~string](str, pattern, replace T) string
- func Reverse[T ~string](s T) string
- func RightTrim[T ~string](str, chars T) string
- func RuneLength[T ~string](str T, params ...string) bool
- func SafeFileName[T ~string](str T) string
- func SetFieldsRequiredByDefault(value bool)
- func SetNilPtrAllowedByRequired(value bool)
- func Sign[V constraints.Integer | constraints.Float](value V) float64
- func Some[T any](array []T, iterator ConditionIterator[T]) bool
- func StringLength[T ~string](str T, params ...string) bool
- func StringMatches[T ~string](str T, params ...T) bool
- func StripLow[T ~string](str T, keepNewLines bool) string
- func ToBoolean[T ~string](str T) (bool, error)
- func ToInt[T any](value T) (res int64, err error)
- func ToJSON[T any](obj T) (string, error)
- func ToNumber[T any, U constraints.Float | constraints.Integer](value T) (res U, err error)
- func ToString[T any](obj T) string
- func Trim[T ~string](str, chars T) string
- func Truncate[T ~string](str T, length int, ending string) T
- func TruncatingErrorf[T ~string](str T, args ...interface{}) error
- func UnderscoreToCamelCase[T ~string](s T) string
- func ValidateArray[T any](array []T, iterator ConditionIterator[T]) bool
- func ValidateMap(s map[string]interface{}, m map[string]interface{}) (bool, error)
- func ValidateMapAsync(s map[string]interface{}, m map[string]interface{}) (<-chan bool, <-chan error)
- func ValidateStruct[T any](s T) (bool, error)
- func ValidateStructAsync[T any](s T) (<-chan bool, <-chan error)
- func WhiteList[T ~string](str, chars T) string
- type ConditionIterator
- type CustomTypeValidator
- type Error
- type Errors
- type ISO3166Entry
- type ISO693Entry
- type InterfaceParamValidator
- type Iterator
- type ParamValidator
- type ReduceIterator
- type ResultIterator
- type UnsupportedTypeError
- type Validator
Examples ¶
Constants ¶
const ( Email string = "" /* 1208-byte string literal not displayed */ CreditCard string = "" /* 231-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 = "" /* 157-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 = `` /* 659-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]*)+/?$` WinARPath string = `` /* 128-byte string literal not displayed */ UnixARPath string = `^((\.{0,2}/)?([^/\x00]*))+/?$` Semver string = "" /* 183-byte string literal not displayed */ IMEI string = "^[0-9a-f]{14}$|^\\d{15}$|^\\d{18}$" IMSI string = "^\\d{14,15}$" E164 string = `^\+?[1-9]\d{1,14}$` )
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
Variables ¶
var CustomTypeTagMap = &customTypeTagMap[any]{validators: make(map[string]CustomTypeValidator[any])}
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"
var ISO4217List = []string{}/* 181 elements not displayed */
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[any]{ "type": IsType[any], }
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[string]{ "length": ByteLength[string], "range": Range[string], "runelength": RuneLength[string], "stringlength": StringLength[string], "matches": StringMatches[string], "in": IsInRaw[string], "rsapub": IsRsaPub[string], "minstringlength": MinStringLength[string], "maxstringlength": MaxStringLength[string], }
ParamTagMap is a map of functions accept variants parameters
var ParamTagRegexMap = map[string]*regexp.Regexp{ "range": regexp.MustCompile("^range\\((\\d+(?:.\\d+)?)\\|(\\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[string]{ "email": IsEmail[string], "url": IsURL[string], "dialstring": IsDialString[string], "requrl": IsRequestURL[string], "requri": IsRequestURI[string], "alpha": IsAlpha[string], "utfletter": IsUTFLetter[string], "alphanum": IsAlphanumeric[string], "utfletternum": IsUTFLetterNumeric[string], "numeric": IsNumeric[string], "utfnumeric": IsUTFNumeric[string], "utfdigit": IsUTFDigit[string], "hexadecimal": IsHexadecimal[string], "hexcolor": IsHexcolor[string], "rgbcolor": IsRGBcolor[string], "lowercase": IsLowerCase[string], "uppercase": IsUpperCase[string], "int": IsInt[string], "float": IsFloat[string], "null": IsNull[string], "notnull": IsNotNull[string], "uuid": IsUUID[string], "uuidv3": IsUUIDv3[string], "uuidv4": IsUUIDv4[string], "uuidv5": IsUUIDv5[string], "creditcard": IsCreditCard[string], "isbn10": IsISBN10[string], "isbn13": IsISBN13[string], "json": IsJSON[string], "multibyte": IsMultibyte[string], "ascii": IsASCII[string], "printableascii": IsPrintableASCII[string], "fullwidth": IsFullWidth[string], "halfwidth": IsHalfWidth[string], "variablewidth": IsVariableWidth[string], "base64": IsBase64[string], "datauri": IsDataURI[string], "ip": IsIP[string], "port": IsPort[string], "ipv4": IsIPv4[string], "ipv6": IsIPv6[string], "dns": IsDNSName[string], "host": IsHost[string], "mac": IsMAC[string], "latitude": IsLatitude[string], "longitude": IsLongitude[string], "ssn": IsSSN[string], "semver": IsSemver[string], "rfc3339": IsRFC3339[string], "rfc3339WithoutZone": IsRFC3339WithoutZone[string], "ISO3166Alpha2": IsISO3166Alpha2[string], "ISO3166Alpha3": IsISO3166Alpha3[string], "ISO4217": IsISO4217[string], "IMEI": IsIMEI[string], "ulid": IsULID[string], }
TagMap is a map of functions, that can be used as tags for ValidateStruct function.
Functions ¶
func Abs ¶
func Abs[V constraints.Integer | constraints.Float](value V) V
Abs returns absolute value of number
Example ¶
_ = Abs(-123.3e1) // 123.3e1 _ = Abs(+0) // 0 _ = Abs(321) // 321
Output:
func ByteLength ¶
ByteLength checks string's length
func CamelCaseToUnderscore ¶
CamelCaseToUnderscore converts from camel case form to underscore separated form. Ex.: MyFunc => my_func
func Count ¶
func Count[T any](array []T, iterator ConditionIterator[T]) int
Count iterates over the slice and apply ConditionIterator to every item. Returns count of items that meets ConditionIterator.
Example ¶
data := []interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} var fn ConditionIterator[any] = func(value interface{}, index int) bool { return value.(int)%2 == 0 } _ = Count(data, fn) // result = 5
Output:
func Each ¶
Each iterates over the slice and apply Iterator to every item
Example ¶
data := []interface{}{1, 2, 3, 4, 5} var fn Iterator[any] = func(value interface{}, index int) { println(value.(int)) } Each(data, fn)
Output:
func ErrorByField ¶
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.
func ErrorsByField ¶
ErrorsByField returns map of errors of the struct validated by ValidateStruct or empty map if there are no errors.
func Every ¶
func Every[T any](array []T, iterator ConditionIterator[T]) bool
Every validates that every item of array corresponds to ConditionIterator. Returns boolean.
func Filter ¶
func Filter[T any](array []T, iterator ConditionIterator[T]) []T
Filter iterates over the slice and apply ConditionIterator to every item. Returns new slice.
Example ¶
data := []interface{}{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} var fn ConditionIterator[any] = func(value interface{}, index int) bool { return value.(int)%2 == 0 } _ = Filter(data, fn) // result = []interface{}{2, 4, 6, 8, 10}
Output:
func Find ¶
func Find[T any](array []T, iterator ConditionIterator[T]) (t T)
Find iterates over the slice and apply ConditionIterator to every item. Returns first item that meet ConditionIterator or nil otherwise.
Example ¶
data := []interface{}{1, 2, 3, 4, 5} var fn ConditionIterator[any] = func(value interface{}, index int) bool { return value.(int) == 4 } _ = Find(data, fn) // result = 4
Output:
func HasLowerCase ¶
HasLowerCase checks if the string contains at least 1 lowercase. Empty string is valid.
func HasUpperCase ¶
HasUpperCase checks if the string contains as least 1 uppercase. Empty string is valid.
func HasWhitespace ¶
HasWhitespace checks if the string contains any whitespace
func HasWhitespaceOnly ¶
HasWhitespaceOnly checks the string only contains whitespace
func InRange ¶
func InRange[V constraints.Ordered](value V, left V, right V) bool
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
Example ¶
_ = InRange(10, 11, 20) // false _ = InRange(10.02, -10.124, 10.234) // true _ = InRange("abc", "a", "cba") // true
Output:
func IsAlphanumeric ¶
IsAlphanumeric checks if the string contains only letters and numbers. Empty string is valid.
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 IsDivisibleBy ¶
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).
Example ¶
This small example illustrate how to work with IsDivisibleBy function.
println("1024 is divisible by 64: ", IsDivisibleBy("1024", "64"))
Output:
func IsExistingEmail ¶
IsExistingEmail checks if the string is an email of existing domain
func IsFilePath ¶
IsFilePath checks is a string is Win or Unix file path and returns it's type.
func IsFullWidth ¶
IsFullWidth checks if the string contains any full-width chars. Empty string is valid.
func IsHalfWidth ¶
IsHalfWidth checks if the string contains any half-width chars. Empty string is valid.
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 IsHexadecimal ¶
IsHexadecimal checks if the string is a hexadecimal number.
func IsHexcolor ¶
IsHexcolor checks if the string is a hexadecimal color.
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 IsISO3166Alpha2 ¶
IsISO3166Alpha2 checks if a string is valid two-letter country code
func IsISO3166Alpha3 ¶
IsISO3166Alpha3 checks if a string is valid three-letter country code
func IsISO693Alpha2 ¶
IsISO693Alpha2 checks if a string is valid two-letter language code
func IsISO693Alpha3b ¶
IsISO693Alpha3b checks if a string is valid three-letter language code
func IsLatitude ¶
IsLatitude checks if a string is valid latitude.
func IsLongitude ¶
IsLongitude checks if a string is valid longitude.
func IsLowerCase ¶
IsLowerCase checks if the string is lowercase. Empty string is valid.
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 IsMongoID ¶
IsMongoID checks if the string is a valid hex-encoded representation of a MongoDB ObjectId.
func IsMultibyte ¶
IsMultibyte checks if the string contains one or more multibyte chars. Empty string is valid.
func IsNatural ¶
func IsNatural[V constraints.Integer | constraints.Float](value V) bool
IsNatural returns true if value is natural number (positive and whole)
Example ¶
_ = IsNatural(1.123) // false _ = IsNatural(1.0) // true _ = IsNatural(-10) // false
Output:
func IsNegative ¶
func IsNegative[V constraints.Integer | constraints.Float](value V) bool
IsNegative returns true if value < 0
Example ¶
_ = IsNegative(-123) // true _ = IsNegative(0) // false _ = IsNegative(123) // false
Output:
func IsNonNegative ¶
func IsNonNegative[V constraints.Integer | constraints.Float](value V) bool
IsNonNegative returns true if value >= 0
Example ¶
_ = IsNonNegative(-123) // false _ = IsNonNegative(0) // true _ = IsNonNegative(123) // true
Output:
func IsNonPositive ¶
func IsNonPositive[V constraints.Integer | constraints.Float](value V) bool
IsNonPositive returns true if value <= 0
Example ¶
_ = IsNonPositive(-123) // true _ = IsNonPositive(0) // true _ = IsNonPositive(123) // false
Output:
func IsPositive ¶
func IsPositive[V constraints.Integer | constraints.Float](value V) bool
IsPositive returns true if value > 0
Example ¶
_ = IsPositive(-123) // false _ = IsPositive(0) // false _ = IsPositive(123) // true
Output:
func IsPrintableASCII ¶
IsPrintableASCII checks if the string contains printable ASCII chars only. Empty string is valid.
func IsRFC3339WithoutZone ¶
IsRFC3339WithoutZone checks if string is valid timestamp value according to RFC3339 which excludes the timezone.
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(str, "ripemd128")`
func IsRipeMD160 ¶
IsRipeMD160 checks is a string is a RipeMD160 hash. Alias for `IsHash(str, "ripemd160")`
func IsRsaPublicKey ¶
IsRsaPublicKey checks if a string is valid public key with provided length
func IsSHA3224 ¶
IsSHA3224 checks is a string is a SHA3-224 hash. Alias for `IsHash(str, "sha3-224")`
func IsSHA3256 ¶
IsSHA3256 checks is a string is a SHA3-256 hash. Alias for `IsHash(str, "sha3-256")`
func IsSHA3384 ¶
IsSHA3384 checks is a string is a SHA3-384 hash. Alias for `IsHash(str, "sha3-384")`
func IsSHA3512 ¶
IsSHA3512 checks is a string is a SHA3-512 hash. Alias for `IsHash(str, "sha3-512")`
func IsTiger128 ¶
IsTiger128 checks is a string is a Tiger128 hash. Alias for `IsHash(str, "tiger128")`
func IsTiger160 ¶
IsTiger160 checks is a string is a Tiger160 hash. Alias for `IsHash(str, "tiger160")`
func IsTiger192 ¶
IsTiger192 checks is a string is a Tiger192 hash. Alias for `IsHash(str, "tiger192")`
func IsULID ¶
IsULID checks if the string is a ULID.
Implementation got from:
https://github.com/oklog/ulid (Apache-2.0 License)
func IsUTFDigit ¶
IsUTFDigit checks if the string contains only unicode radix-10 decimal digits. Empty string is valid.
func IsUTFLetter ¶
IsUTFLetter checks if the string contains only unicode letter characters. Similar to IsAlpha but for all languages. Empty string is valid.
func IsUTFLetterNumeric ¶
IsUTFLetterNumeric checks if the string contains only unicode letters and numbers. Empty string is valid.
func IsUTFNumeric ¶
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.
func IsUnixFilePath ¶
IsUnixFilePath checks both relative & absolute paths in Unix
func IsUnixTime ¶
IsUnixTime checks if string is valid unix timestamp value
func IsUpperCase ¶
IsUpperCase checks if the string is uppercase. Empty string is valid.
func IsVariableWidth ¶
IsVariableWidth checks if the string contains a mixture of full and half-width chars. Empty string is valid.
func IsWhole ¶
func IsWhole[V constraints.Integer | constraints.Float](value V) bool
IsWhole returns true if value is whole number
Example ¶
_ = IsWhole(1.123) // false _ = IsWhole(1.0) // true _ = IsWhole(10) // true
Output:
func IsWinFilePath ¶
IsWinFilePath checks both relative & absolute paths in Windows
func LeftTrim ¶
LeftTrim trims characters from the left side of the input. If second argument is empty, it will remove leading spaces.
func Map ¶
func Map[T any](array []T, iterator ResultIterator[T]) []T
Map iterates over the slice and apply ResultIterator to every item. Returns new slice as a result.
Example ¶
data := []interface{}{1, 2, 3, 4, 5} var fn ResultIterator[any] = func(value interface{}, index int) interface{} { return value.(int) * 3 } _ = Map(data, fn) // result = []interface{}{1, 6, 9, 12, 15}
Output:
func Matches ¶
Matches checks if string matches the pattern (pattern is regular expression) In case of error return false
func MaxStringLength ¶
MaxStringLength checks string's maximum length (including multi byte strings)
func MinStringLength ¶
MinStringLength checks string's minimum length (including multi byte strings)
func NormalizeEmail ¶
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.
func PadBoth ¶
PadBoth pads both sides of a string if size of string is less then indicated pad length
func PadLeft ¶
PadLeft pads left side of a string if size of string is less then indicated pad length
func PadRight ¶
PadRight pads right side of a string if size of string is less then indicated pad length
func Reduce ¶
func Reduce[T any](array []T, iterator ReduceIterator[T], initialValue T) T
Reduce boils down a list of values into a single value by ReduceIterator
func RemoveTags ¶
RemoveTags removes all tags from HTML string
func ReplacePattern ¶
ReplacePattern replaces regular expression pattern in string
Example ¶
// 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")
Output:
func RightTrim ¶
RightTrim trims characters from the right side of the input. If second argument is empty, it will remove trailing spaces.
func RuneLength ¶
RuneLength checks string's length Alias for StringLength
func SafeFileName ¶
SafeFileName returns safe string that can be used in file names
func SetFieldsRequiredByDefault ¶
func SetFieldsRequiredByDefault(value bool)
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"`
func SetNilPtrAllowedByRequired ¶
func SetNilPtrAllowedByRequired(value bool)
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.
func Sign ¶
func Sign[V constraints.Integer | constraints.Float](value V) float64
Sign returns signum of number: 1 in case of value > 0, -1 in case of value < 0, 0 otherwise
Example ¶
_ = Sign(-123) // -1 _ = Sign(123) // 1 _ = Sign(0) // 0
Output:
func Some ¶
func Some[T any](array []T, iterator ConditionIterator[T]) bool
Some validates that any item of array corresponds to ConditionIterator. Returns boolean.
func StringLength ¶
StringLength checks string's length (including multi byte strings)
func StringMatches ¶
StringMatches checks if a string matches a given pattern.
func StripLow ¶
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).
func ToBoolean ¶
ToBoolean convert the input string to a boolean.
Example ¶
// 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
Output:
func ToInt ¶
ToInt convert the input string or any int type to an integer type 64, or 0 if the input is not an integer.
Example ¶
_, _ = ToInt(1.0) // 1, nil _, _ = ToInt("-124") // -124, nil _, _ = ToInt("false") // 0, error
Output:
func ToJSON ¶
ToJSON convert the input to a valid JSON string
Example ¶
_, _ = ToJSON([]int{1, 2, 3}) // [1, 2, 3] _, _ = ToJSON(map[int]int{1: 2, 2: 3}) // { "1": 2, "2": 3 } _, _ = ToJSON(func() {}) // error
Output:
func ToNumber ¶ added in v0.0.3
func ToNumber[T any, U constraints.Float | constraints.Integer](value T) (res U, err error)
ToNumber convert the input string to a number, or 0.0 if the input is not a number.
func ToString ¶
ToString convert the input to a string.
Example ¶
_ = ToString(new(interface{})) // 0xc000090200 _ = ToString(time.Second + time.Hour) // 1h1s _ = ToString(123) // 123
Output:
func Trim ¶
Trim trims characters from both sides of the input. If second argument is empty, it will remove spaces.
Example ¶
// 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")
Output:
func TruncatingErrorf ¶
TruncatingErrorf removes extra args from fmt.Errorf if not formatted in the str object
func UnderscoreToCamelCase ¶
UnderscoreToCamelCase converts from underscore separated form to camel case form. Ex.: my_func => MyFunc
func ValidateArray ¶
func ValidateArray[T any](array []T, iterator ConditionIterator[T]) bool
ValidateArray performs validation according to condition iterator that validates every element of the array
func ValidateMap ¶
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 ¶
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
func ValidateStruct ¶
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)
Example ¶
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[string](func(str string) bool { return str == "duck" }) result, err := ValidateStruct(post) if err != nil { println("error: " + err.Error()) } println(result)
Output:
func ValidateStructAsync ¶
ValidateStructAsync performs async validation of the struct and returns results through the channels
Types ¶
type ConditionIterator ¶
ConditionIterator is the function that accepts element of slice/array and its index and returns boolean
type CustomTypeValidator ¶
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 ¶
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.
type Errors ¶
type Errors []error
Errors is an array of multiple errors and conforms to the error interface.
type ISO3166Entry ¶
type ISO3166Entry struct { EnglishShortName string FrenchShortName string Alpha2Code string Alpha3Code string Numeric string }
ISO3166Entry stores country codes
type ISO693Entry ¶
ISO693Entry stores ISO language codes
type InterfaceParamValidator ¶
InterfaceParamValidator is a wrapper for functions that accept variants parameters for an interface value
type ParamValidator ¶
ParamValidator is a wrapper for validator functions that accept additional parameters.
type ReduceIterator ¶
type ReduceIterator[T any] func(T, T) T
ReduceIterator is the function that accepts two element of slice/array and returns result of merging those values
type ResultIterator ¶
ResultIterator is the function that accepts element of slice/array and its index and returns any result
type UnsupportedTypeError ¶
UnsupportedTypeError is a wrapper for reflect.Type
func (*UnsupportedTypeError) Error ¶
func (e *UnsupportedTypeError) Error() string
Error returns string equivalent for reflect.Type