baked_in.go 86 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999
  1. package validator
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/sha256"
  6. "encoding/hex"
  7. "encoding/json"
  8. "fmt"
  9. "io/fs"
  10. "net"
  11. "net/url"
  12. "os"
  13. "reflect"
  14. "strconv"
  15. "strings"
  16. "sync"
  17. "syscall"
  18. "time"
  19. "unicode/utf8"
  20. "golang.org/x/crypto/sha3"
  21. "golang.org/x/text/language"
  22. "github.com/gabriel-vasile/mimetype"
  23. urn "github.com/leodido/go-urn"
  24. )
  25. // Func accepts a FieldLevel interface for all validation needs. The return
  26. // value should be true when validation succeeds.
  27. type Func func(fl FieldLevel) bool
  28. // FuncCtx accepts a context.Context and FieldLevel interface for all
  29. // validation needs. The return value should be true when validation succeeds.
  30. type FuncCtx func(ctx context.Context, fl FieldLevel) bool
  31. // wrapFunc wraps normal Func makes it compatible with FuncCtx
  32. func wrapFunc(fn Func) FuncCtx {
  33. if fn == nil {
  34. return nil // be sure not to wrap a bad function.
  35. }
  36. return func(ctx context.Context, fl FieldLevel) bool {
  37. return fn(fl)
  38. }
  39. }
  40. var (
  41. restrictedTags = map[string]struct{}{
  42. diveTag: {},
  43. keysTag: {},
  44. endKeysTag: {},
  45. structOnlyTag: {},
  46. omitempty: {},
  47. omitnil: {},
  48. skipValidationTag: {},
  49. utf8HexComma: {},
  50. utf8Pipe: {},
  51. noStructLevelTag: {},
  52. requiredTag: {},
  53. isdefault: {},
  54. }
  55. // bakedInAliases is a default mapping of a single validation tag that
  56. // defines a common or complex set of validation(s) to simplify
  57. // adding validation to structs.
  58. bakedInAliases = map[string]string{
  59. "iscolor": "hexcolor|rgb|rgba|hsl|hsla",
  60. "country_code": "iso3166_1_alpha2|iso3166_1_alpha3|iso3166_1_alpha_numeric",
  61. "eu_country_code": "iso3166_1_alpha2_eu|iso3166_1_alpha3_eu|iso3166_1_alpha_numeric_eu",
  62. }
  63. // bakedInValidators is the default map of ValidationFunc
  64. // you can add, remove or even replace items to suite your needs,
  65. // or even disregard and use your own map if so desired.
  66. bakedInValidators = map[string]Func{
  67. "required": hasValue,
  68. "required_if": requiredIf,
  69. "required_unless": requiredUnless,
  70. "skip_unless": skipUnless,
  71. "required_with": requiredWith,
  72. "required_with_all": requiredWithAll,
  73. "required_without": requiredWithout,
  74. "required_without_all": requiredWithoutAll,
  75. "excluded_if": excludedIf,
  76. "excluded_unless": excludedUnless,
  77. "excluded_with": excludedWith,
  78. "excluded_with_all": excludedWithAll,
  79. "excluded_without": excludedWithout,
  80. "excluded_without_all": excludedWithoutAll,
  81. "isdefault": isDefault,
  82. "len": hasLengthOf,
  83. "min": hasMinOf,
  84. "max": hasMaxOf,
  85. "eq": isEq,
  86. "eq_ignore_case": isEqIgnoreCase,
  87. "ne": isNe,
  88. "ne_ignore_case": isNeIgnoreCase,
  89. "lt": isLt,
  90. "lte": isLte,
  91. "gt": isGt,
  92. "gte": isGte,
  93. "eqfield": isEqField,
  94. "eqcsfield": isEqCrossStructField,
  95. "necsfield": isNeCrossStructField,
  96. "gtcsfield": isGtCrossStructField,
  97. "gtecsfield": isGteCrossStructField,
  98. "ltcsfield": isLtCrossStructField,
  99. "ltecsfield": isLteCrossStructField,
  100. "nefield": isNeField,
  101. "gtefield": isGteField,
  102. "gtfield": isGtField,
  103. "ltefield": isLteField,
  104. "ltfield": isLtField,
  105. "fieldcontains": fieldContains,
  106. "fieldexcludes": fieldExcludes,
  107. "alpha": isAlpha,
  108. "alphanum": isAlphanum,
  109. "alphaunicode": isAlphaUnicode,
  110. "alphanumunicode": isAlphanumUnicode,
  111. "boolean": isBoolean,
  112. "numeric": isNumeric,
  113. "number": isNumber,
  114. "hexadecimal": isHexadecimal,
  115. "hexcolor": isHEXColor,
  116. "rgb": isRGB,
  117. "rgba": isRGBA,
  118. "hsl": isHSL,
  119. "hsla": isHSLA,
  120. "e164": isE164,
  121. "email": isEmail,
  122. "url": isURL,
  123. "http_url": isHttpURL,
  124. "uri": isURI,
  125. "urn_rfc2141": isUrnRFC2141, // RFC 2141
  126. "file": isFile,
  127. "filepath": isFilePath,
  128. "base32": isBase32,
  129. "base64": isBase64,
  130. "base64url": isBase64URL,
  131. "base64rawurl": isBase64RawURL,
  132. "contains": contains,
  133. "containsany": containsAny,
  134. "containsrune": containsRune,
  135. "excludes": excludes,
  136. "excludesall": excludesAll,
  137. "excludesrune": excludesRune,
  138. "startswith": startsWith,
  139. "endswith": endsWith,
  140. "startsnotwith": startsNotWith,
  141. "endsnotwith": endsNotWith,
  142. "image": isImage,
  143. "isbn": isISBN,
  144. "isbn10": isISBN10,
  145. "isbn13": isISBN13,
  146. "issn": isISSN,
  147. "eth_addr": isEthereumAddress,
  148. "eth_addr_checksum": isEthereumAddressChecksum,
  149. "btc_addr": isBitcoinAddress,
  150. "btc_addr_bech32": isBitcoinBech32Address,
  151. "uuid": isUUID,
  152. "uuid3": isUUID3,
  153. "uuid4": isUUID4,
  154. "uuid5": isUUID5,
  155. "uuid_rfc4122": isUUIDRFC4122,
  156. "uuid3_rfc4122": isUUID3RFC4122,
  157. "uuid4_rfc4122": isUUID4RFC4122,
  158. "uuid5_rfc4122": isUUID5RFC4122,
  159. "ulid": isULID,
  160. "md4": isMD4,
  161. "md5": isMD5,
  162. "sha256": isSHA256,
  163. "sha384": isSHA384,
  164. "sha512": isSHA512,
  165. "ripemd128": isRIPEMD128,
  166. "ripemd160": isRIPEMD160,
  167. "tiger128": isTIGER128,
  168. "tiger160": isTIGER160,
  169. "tiger192": isTIGER192,
  170. "ascii": isASCII,
  171. "printascii": isPrintableASCII,
  172. "multibyte": hasMultiByteCharacter,
  173. "datauri": isDataURI,
  174. "latitude": isLatitude,
  175. "longitude": isLongitude,
  176. "ssn": isSSN,
  177. "ipv4": isIPv4,
  178. "ipv6": isIPv6,
  179. "ip": isIP,
  180. "cidrv4": isCIDRv4,
  181. "cidrv6": isCIDRv6,
  182. "cidr": isCIDR,
  183. "tcp4_addr": isTCP4AddrResolvable,
  184. "tcp6_addr": isTCP6AddrResolvable,
  185. "tcp_addr": isTCPAddrResolvable,
  186. "udp4_addr": isUDP4AddrResolvable,
  187. "udp6_addr": isUDP6AddrResolvable,
  188. "udp_addr": isUDPAddrResolvable,
  189. "ip4_addr": isIP4AddrResolvable,
  190. "ip6_addr": isIP6AddrResolvable,
  191. "ip_addr": isIPAddrResolvable,
  192. "unix_addr": isUnixAddrResolvable,
  193. "mac": isMAC,
  194. "hostname": isHostnameRFC952, // RFC 952
  195. "hostname_rfc1123": isHostnameRFC1123, // RFC 1123
  196. "fqdn": isFQDN,
  197. "unique": isUnique,
  198. "oneof": isOneOf,
  199. "html": isHTML,
  200. "html_encoded": isHTMLEncoded,
  201. "url_encoded": isURLEncoded,
  202. "dir": isDir,
  203. "dirpath": isDirPath,
  204. "json": isJSON,
  205. "jwt": isJWT,
  206. "hostname_port": isHostnamePort,
  207. "lowercase": isLowercase,
  208. "uppercase": isUppercase,
  209. "datetime": isDatetime,
  210. "timezone": isTimeZone,
  211. "iso3166_1_alpha2": isIso3166Alpha2,
  212. "iso3166_1_alpha2_eu": isIso3166Alpha2EU,
  213. "iso3166_1_alpha3": isIso3166Alpha3,
  214. "iso3166_1_alpha3_eu": isIso3166Alpha3EU,
  215. "iso3166_1_alpha_numeric": isIso3166AlphaNumeric,
  216. "iso3166_1_alpha_numeric_eu": isIso3166AlphaNumericEU,
  217. "iso3166_2": isIso31662,
  218. "iso4217": isIso4217,
  219. "iso4217_numeric": isIso4217Numeric,
  220. "bcp47_language_tag": isBCP47LanguageTag,
  221. "postcode_iso3166_alpha2": isPostcodeByIso3166Alpha2,
  222. "postcode_iso3166_alpha2_field": isPostcodeByIso3166Alpha2Field,
  223. "bic": isIsoBicFormat,
  224. "semver": isSemverFormat,
  225. "dns_rfc1035_label": isDnsRFC1035LabelFormat,
  226. "credit_card": isCreditCard,
  227. "cve": isCveFormat,
  228. "luhn_checksum": hasLuhnChecksum,
  229. "mongodb": isMongoDB,
  230. "cron": isCron,
  231. "spicedb": isSpiceDB,
  232. }
  233. )
  234. var (
  235. oneofValsCache = map[string][]string{}
  236. oneofValsCacheRWLock = sync.RWMutex{}
  237. )
  238. func parseOneOfParam2(s string) []string {
  239. oneofValsCacheRWLock.RLock()
  240. vals, ok := oneofValsCache[s]
  241. oneofValsCacheRWLock.RUnlock()
  242. if !ok {
  243. oneofValsCacheRWLock.Lock()
  244. vals = splitParamsRegex.FindAllString(s, -1)
  245. for i := 0; i < len(vals); i++ {
  246. vals[i] = strings.Replace(vals[i], "'", "", -1)
  247. }
  248. oneofValsCache[s] = vals
  249. oneofValsCacheRWLock.Unlock()
  250. }
  251. return vals
  252. }
  253. func isURLEncoded(fl FieldLevel) bool {
  254. return uRLEncodedRegex.MatchString(fl.Field().String())
  255. }
  256. func isHTMLEncoded(fl FieldLevel) bool {
  257. return hTMLEncodedRegex.MatchString(fl.Field().String())
  258. }
  259. func isHTML(fl FieldLevel) bool {
  260. return hTMLRegex.MatchString(fl.Field().String())
  261. }
  262. func isOneOf(fl FieldLevel) bool {
  263. vals := parseOneOfParam2(fl.Param())
  264. field := fl.Field()
  265. var v string
  266. switch field.Kind() {
  267. case reflect.String:
  268. v = field.String()
  269. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  270. v = strconv.FormatInt(field.Int(), 10)
  271. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  272. v = strconv.FormatUint(field.Uint(), 10)
  273. default:
  274. panic(fmt.Sprintf("Bad field type %T", field.Interface()))
  275. }
  276. for i := 0; i < len(vals); i++ {
  277. if vals[i] == v {
  278. return true
  279. }
  280. }
  281. return false
  282. }
  283. // isUnique is the validation function for validating if each array|slice|map value is unique
  284. func isUnique(fl FieldLevel) bool {
  285. field := fl.Field()
  286. param := fl.Param()
  287. v := reflect.ValueOf(struct{}{})
  288. switch field.Kind() {
  289. case reflect.Slice, reflect.Array:
  290. elem := field.Type().Elem()
  291. if elem.Kind() == reflect.Ptr {
  292. elem = elem.Elem()
  293. }
  294. if param == "" {
  295. m := reflect.MakeMap(reflect.MapOf(elem, v.Type()))
  296. for i := 0; i < field.Len(); i++ {
  297. m.SetMapIndex(reflect.Indirect(field.Index(i)), v)
  298. }
  299. return field.Len() == m.Len()
  300. }
  301. sf, ok := elem.FieldByName(param)
  302. if !ok {
  303. panic(fmt.Sprintf("Bad field name %s", param))
  304. }
  305. sfTyp := sf.Type
  306. if sfTyp.Kind() == reflect.Ptr {
  307. sfTyp = sfTyp.Elem()
  308. }
  309. m := reflect.MakeMap(reflect.MapOf(sfTyp, v.Type()))
  310. var fieldlen int
  311. for i := 0; i < field.Len(); i++ {
  312. key := reflect.Indirect(reflect.Indirect(field.Index(i)).FieldByName(param))
  313. if key.IsValid() {
  314. fieldlen++
  315. m.SetMapIndex(key, v)
  316. }
  317. }
  318. return fieldlen == m.Len()
  319. case reflect.Map:
  320. var m reflect.Value
  321. if field.Type().Elem().Kind() == reflect.Ptr {
  322. m = reflect.MakeMap(reflect.MapOf(field.Type().Elem().Elem(), v.Type()))
  323. } else {
  324. m = reflect.MakeMap(reflect.MapOf(field.Type().Elem(), v.Type()))
  325. }
  326. for _, k := range field.MapKeys() {
  327. m.SetMapIndex(reflect.Indirect(field.MapIndex(k)), v)
  328. }
  329. return field.Len() == m.Len()
  330. default:
  331. if parent := fl.Parent(); parent.Kind() == reflect.Struct {
  332. uniqueField := parent.FieldByName(param)
  333. if uniqueField == reflect.ValueOf(nil) {
  334. panic(fmt.Sprintf("Bad field name provided %s", param))
  335. }
  336. if uniqueField.Kind() != field.Kind() {
  337. panic(fmt.Sprintf("Bad field type %T:%T", field.Interface(), uniqueField.Interface()))
  338. }
  339. return field.Interface() != uniqueField.Interface()
  340. }
  341. panic(fmt.Sprintf("Bad field type %T", field.Interface()))
  342. }
  343. }
  344. // isMAC is the validation function for validating if the field's value is a valid MAC address.
  345. func isMAC(fl FieldLevel) bool {
  346. _, err := net.ParseMAC(fl.Field().String())
  347. return err == nil
  348. }
  349. // isCIDRv4 is the validation function for validating if the field's value is a valid v4 CIDR address.
  350. func isCIDRv4(fl FieldLevel) bool {
  351. ip, net, err := net.ParseCIDR(fl.Field().String())
  352. return err == nil && ip.To4() != nil && net.IP.Equal(ip)
  353. }
  354. // isCIDRv6 is the validation function for validating if the field's value is a valid v6 CIDR address.
  355. func isCIDRv6(fl FieldLevel) bool {
  356. ip, _, err := net.ParseCIDR(fl.Field().String())
  357. return err == nil && ip.To4() == nil
  358. }
  359. // isCIDR is the validation function for validating if the field's value is a valid v4 or v6 CIDR address.
  360. func isCIDR(fl FieldLevel) bool {
  361. _, _, err := net.ParseCIDR(fl.Field().String())
  362. return err == nil
  363. }
  364. // isIPv4 is the validation function for validating if a value is a valid v4 IP address.
  365. func isIPv4(fl FieldLevel) bool {
  366. ip := net.ParseIP(fl.Field().String())
  367. return ip != nil && ip.To4() != nil
  368. }
  369. // isIPv6 is the validation function for validating if the field's value is a valid v6 IP address.
  370. func isIPv6(fl FieldLevel) bool {
  371. ip := net.ParseIP(fl.Field().String())
  372. return ip != nil && ip.To4() == nil
  373. }
  374. // isIP is the validation function for validating if the field's value is a valid v4 or v6 IP address.
  375. func isIP(fl FieldLevel) bool {
  376. ip := net.ParseIP(fl.Field().String())
  377. return ip != nil
  378. }
  379. // isSSN is the validation function for validating if the field's value is a valid SSN.
  380. func isSSN(fl FieldLevel) bool {
  381. field := fl.Field()
  382. if field.Len() != 11 {
  383. return false
  384. }
  385. return sSNRegex.MatchString(field.String())
  386. }
  387. // isLongitude is the validation function for validating if the field's value is a valid longitude coordinate.
  388. func isLongitude(fl FieldLevel) bool {
  389. field := fl.Field()
  390. var v string
  391. switch field.Kind() {
  392. case reflect.String:
  393. v = field.String()
  394. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  395. v = strconv.FormatInt(field.Int(), 10)
  396. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  397. v = strconv.FormatUint(field.Uint(), 10)
  398. case reflect.Float32:
  399. v = strconv.FormatFloat(field.Float(), 'f', -1, 32)
  400. case reflect.Float64:
  401. v = strconv.FormatFloat(field.Float(), 'f', -1, 64)
  402. default:
  403. panic(fmt.Sprintf("Bad field type %T", field.Interface()))
  404. }
  405. return longitudeRegex.MatchString(v)
  406. }
  407. // isLatitude is the validation function for validating if the field's value is a valid latitude coordinate.
  408. func isLatitude(fl FieldLevel) bool {
  409. field := fl.Field()
  410. var v string
  411. switch field.Kind() {
  412. case reflect.String:
  413. v = field.String()
  414. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  415. v = strconv.FormatInt(field.Int(), 10)
  416. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  417. v = strconv.FormatUint(field.Uint(), 10)
  418. case reflect.Float32:
  419. v = strconv.FormatFloat(field.Float(), 'f', -1, 32)
  420. case reflect.Float64:
  421. v = strconv.FormatFloat(field.Float(), 'f', -1, 64)
  422. default:
  423. panic(fmt.Sprintf("Bad field type %T", field.Interface()))
  424. }
  425. return latitudeRegex.MatchString(v)
  426. }
  427. // isDataURI is the validation function for validating if the field's value is a valid data URI.
  428. func isDataURI(fl FieldLevel) bool {
  429. uri := strings.SplitN(fl.Field().String(), ",", 2)
  430. if len(uri) != 2 {
  431. return false
  432. }
  433. if !dataURIRegex.MatchString(uri[0]) {
  434. return false
  435. }
  436. return base64Regex.MatchString(uri[1])
  437. }
  438. // hasMultiByteCharacter is the validation function for validating if the field's value has a multi byte character.
  439. func hasMultiByteCharacter(fl FieldLevel) bool {
  440. field := fl.Field()
  441. if field.Len() == 0 {
  442. return true
  443. }
  444. return multibyteRegex.MatchString(field.String())
  445. }
  446. // isPrintableASCII is the validation function for validating if the field's value is a valid printable ASCII character.
  447. func isPrintableASCII(fl FieldLevel) bool {
  448. return printableASCIIRegex.MatchString(fl.Field().String())
  449. }
  450. // isASCII is the validation function for validating if the field's value is a valid ASCII character.
  451. func isASCII(fl FieldLevel) bool {
  452. return aSCIIRegex.MatchString(fl.Field().String())
  453. }
  454. // isUUID5 is the validation function for validating if the field's value is a valid v5 UUID.
  455. func isUUID5(fl FieldLevel) bool {
  456. return fieldMatchesRegexByStringerValOrString(uUID5Regex, fl)
  457. }
  458. // isUUID4 is the validation function for validating if the field's value is a valid v4 UUID.
  459. func isUUID4(fl FieldLevel) bool {
  460. return fieldMatchesRegexByStringerValOrString(uUID4Regex, fl)
  461. }
  462. // isUUID3 is the validation function for validating if the field's value is a valid v3 UUID.
  463. func isUUID3(fl FieldLevel) bool {
  464. return fieldMatchesRegexByStringerValOrString(uUID3Regex, fl)
  465. }
  466. // isUUID is the validation function for validating if the field's value is a valid UUID of any version.
  467. func isUUID(fl FieldLevel) bool {
  468. return fieldMatchesRegexByStringerValOrString(uUIDRegex, fl)
  469. }
  470. // isUUID5RFC4122 is the validation function for validating if the field's value is a valid RFC4122 v5 UUID.
  471. func isUUID5RFC4122(fl FieldLevel) bool {
  472. return fieldMatchesRegexByStringerValOrString(uUID5RFC4122Regex, fl)
  473. }
  474. // isUUID4RFC4122 is the validation function for validating if the field's value is a valid RFC4122 v4 UUID.
  475. func isUUID4RFC4122(fl FieldLevel) bool {
  476. return fieldMatchesRegexByStringerValOrString(uUID4RFC4122Regex, fl)
  477. }
  478. // isUUID3RFC4122 is the validation function for validating if the field's value is a valid RFC4122 v3 UUID.
  479. func isUUID3RFC4122(fl FieldLevel) bool {
  480. return fieldMatchesRegexByStringerValOrString(uUID3RFC4122Regex, fl)
  481. }
  482. // isUUIDRFC4122 is the validation function for validating if the field's value is a valid RFC4122 UUID of any version.
  483. func isUUIDRFC4122(fl FieldLevel) bool {
  484. return fieldMatchesRegexByStringerValOrString(uUIDRFC4122Regex, fl)
  485. }
  486. // isULID is the validation function for validating if the field's value is a valid ULID.
  487. func isULID(fl FieldLevel) bool {
  488. return fieldMatchesRegexByStringerValOrString(uLIDRegex, fl)
  489. }
  490. // isMD4 is the validation function for validating if the field's value is a valid MD4.
  491. func isMD4(fl FieldLevel) bool {
  492. return md4Regex.MatchString(fl.Field().String())
  493. }
  494. // isMD5 is the validation function for validating if the field's value is a valid MD5.
  495. func isMD5(fl FieldLevel) bool {
  496. return md5Regex.MatchString(fl.Field().String())
  497. }
  498. // isSHA256 is the validation function for validating if the field's value is a valid SHA256.
  499. func isSHA256(fl FieldLevel) bool {
  500. return sha256Regex.MatchString(fl.Field().String())
  501. }
  502. // isSHA384 is the validation function for validating if the field's value is a valid SHA384.
  503. func isSHA384(fl FieldLevel) bool {
  504. return sha384Regex.MatchString(fl.Field().String())
  505. }
  506. // isSHA512 is the validation function for validating if the field's value is a valid SHA512.
  507. func isSHA512(fl FieldLevel) bool {
  508. return sha512Regex.MatchString(fl.Field().String())
  509. }
  510. // isRIPEMD128 is the validation function for validating if the field's value is a valid PIPEMD128.
  511. func isRIPEMD128(fl FieldLevel) bool {
  512. return ripemd128Regex.MatchString(fl.Field().String())
  513. }
  514. // isRIPEMD160 is the validation function for validating if the field's value is a valid PIPEMD160.
  515. func isRIPEMD160(fl FieldLevel) bool {
  516. return ripemd160Regex.MatchString(fl.Field().String())
  517. }
  518. // isTIGER128 is the validation function for validating if the field's value is a valid TIGER128.
  519. func isTIGER128(fl FieldLevel) bool {
  520. return tiger128Regex.MatchString(fl.Field().String())
  521. }
  522. // isTIGER160 is the validation function for validating if the field's value is a valid TIGER160.
  523. func isTIGER160(fl FieldLevel) bool {
  524. return tiger160Regex.MatchString(fl.Field().String())
  525. }
  526. // isTIGER192 is the validation function for validating if the field's value is a valid isTIGER192.
  527. func isTIGER192(fl FieldLevel) bool {
  528. return tiger192Regex.MatchString(fl.Field().String())
  529. }
  530. // isISBN is the validation function for validating if the field's value is a valid v10 or v13 ISBN.
  531. func isISBN(fl FieldLevel) bool {
  532. return isISBN10(fl) || isISBN13(fl)
  533. }
  534. // isISBN13 is the validation function for validating if the field's value is a valid v13 ISBN.
  535. func isISBN13(fl FieldLevel) bool {
  536. s := strings.Replace(strings.Replace(fl.Field().String(), "-", "", 4), " ", "", 4)
  537. if !iSBN13Regex.MatchString(s) {
  538. return false
  539. }
  540. var checksum int32
  541. var i int32
  542. factor := []int32{1, 3}
  543. for i = 0; i < 12; i++ {
  544. checksum += factor[i%2] * int32(s[i]-'0')
  545. }
  546. return (int32(s[12]-'0'))-((10-(checksum%10))%10) == 0
  547. }
  548. // isISBN10 is the validation function for validating if the field's value is a valid v10 ISBN.
  549. func isISBN10(fl FieldLevel) bool {
  550. s := strings.Replace(strings.Replace(fl.Field().String(), "-", "", 3), " ", "", 3)
  551. if !iSBN10Regex.MatchString(s) {
  552. return false
  553. }
  554. var checksum int32
  555. var i int32
  556. for i = 0; i < 9; i++ {
  557. checksum += (i + 1) * int32(s[i]-'0')
  558. }
  559. if s[9] == 'X' {
  560. checksum += 10 * 10
  561. } else {
  562. checksum += 10 * int32(s[9]-'0')
  563. }
  564. return checksum%11 == 0
  565. }
  566. // isISSN is the validation function for validating if the field's value is a valid ISSN.
  567. func isISSN(fl FieldLevel) bool {
  568. s := fl.Field().String()
  569. if !iSSNRegex.MatchString(s) {
  570. return false
  571. }
  572. s = strings.ReplaceAll(s, "-", "")
  573. pos := 8
  574. checksum := 0
  575. for i := 0; i < 7; i++ {
  576. checksum += pos * int(s[i]-'0')
  577. pos--
  578. }
  579. if s[7] == 'X' {
  580. checksum += 10
  581. } else {
  582. checksum += int(s[7] - '0')
  583. }
  584. return checksum%11 == 0
  585. }
  586. // isEthereumAddress is the validation function for validating if the field's value is a valid Ethereum address.
  587. func isEthereumAddress(fl FieldLevel) bool {
  588. address := fl.Field().String()
  589. return ethAddressRegex.MatchString(address)
  590. }
  591. // isEthereumAddressChecksum is the validation function for validating if the field's value is a valid checksumed Ethereum address.
  592. func isEthereumAddressChecksum(fl FieldLevel) bool {
  593. address := fl.Field().String()
  594. if !ethAddressRegex.MatchString(address) {
  595. return false
  596. }
  597. // Checksum validation. Reference: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-55.md
  598. address = address[2:] // Skip "0x" prefix.
  599. h := sha3.NewLegacyKeccak256()
  600. // hash.Hash's io.Writer implementation says it never returns an error. https://golang.org/pkg/hash/#Hash
  601. _, _ = h.Write([]byte(strings.ToLower(address)))
  602. hash := hex.EncodeToString(h.Sum(nil))
  603. for i := 0; i < len(address); i++ {
  604. if address[i] <= '9' { // Skip 0-9 digits: they don't have upper/lower-case.
  605. continue
  606. }
  607. if hash[i] > '7' && address[i] >= 'a' || hash[i] <= '7' && address[i] <= 'F' {
  608. return false
  609. }
  610. }
  611. return true
  612. }
  613. // isBitcoinAddress is the validation function for validating if the field's value is a valid btc address
  614. func isBitcoinAddress(fl FieldLevel) bool {
  615. address := fl.Field().String()
  616. if !btcAddressRegex.MatchString(address) {
  617. return false
  618. }
  619. alphabet := []byte("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")
  620. decode := [25]byte{}
  621. for _, n := range []byte(address) {
  622. d := bytes.IndexByte(alphabet, n)
  623. for i := 24; i >= 0; i-- {
  624. d += 58 * int(decode[i])
  625. decode[i] = byte(d % 256)
  626. d /= 256
  627. }
  628. }
  629. h := sha256.New()
  630. _, _ = h.Write(decode[:21])
  631. d := h.Sum([]byte{})
  632. h = sha256.New()
  633. _, _ = h.Write(d)
  634. validchecksum := [4]byte{}
  635. computedchecksum := [4]byte{}
  636. copy(computedchecksum[:], h.Sum(d[:0]))
  637. copy(validchecksum[:], decode[21:])
  638. return validchecksum == computedchecksum
  639. }
  640. // isBitcoinBech32Address is the validation function for validating if the field's value is a valid bech32 btc address
  641. func isBitcoinBech32Address(fl FieldLevel) bool {
  642. address := fl.Field().String()
  643. if !btcLowerAddressRegexBech32.MatchString(address) && !btcUpperAddressRegexBech32.MatchString(address) {
  644. return false
  645. }
  646. am := len(address) % 8
  647. if am == 0 || am == 3 || am == 5 {
  648. return false
  649. }
  650. address = strings.ToLower(address)
  651. alphabet := "qpzry9x8gf2tvdw0s3jn54khce6mua7l"
  652. hr := []int{3, 3, 0, 2, 3} // the human readable part will always be bc
  653. addr := address[3:]
  654. dp := make([]int, 0, len(addr))
  655. for _, c := range addr {
  656. dp = append(dp, strings.IndexRune(alphabet, c))
  657. }
  658. ver := dp[0]
  659. if ver < 0 || ver > 16 {
  660. return false
  661. }
  662. if ver == 0 {
  663. if len(address) != 42 && len(address) != 62 {
  664. return false
  665. }
  666. }
  667. values := append(hr, dp...)
  668. GEN := []int{0x3b6a57b2, 0x26508e6d, 0x1ea119fa, 0x3d4233dd, 0x2a1462b3}
  669. p := 1
  670. for _, v := range values {
  671. b := p >> 25
  672. p = (p&0x1ffffff)<<5 ^ v
  673. for i := 0; i < 5; i++ {
  674. if (b>>uint(i))&1 == 1 {
  675. p ^= GEN[i]
  676. }
  677. }
  678. }
  679. if p != 1 {
  680. return false
  681. }
  682. b := uint(0)
  683. acc := 0
  684. mv := (1 << 5) - 1
  685. var sw []int
  686. for _, v := range dp[1 : len(dp)-6] {
  687. acc = (acc << 5) | v
  688. b += 5
  689. for b >= 8 {
  690. b -= 8
  691. sw = append(sw, (acc>>b)&mv)
  692. }
  693. }
  694. if len(sw) < 2 || len(sw) > 40 {
  695. return false
  696. }
  697. return true
  698. }
  699. // excludesRune is the validation function for validating that the field's value does not contain the rune specified within the param.
  700. func excludesRune(fl FieldLevel) bool {
  701. return !containsRune(fl)
  702. }
  703. // excludesAll is the validation function for validating that the field's value does not contain any of the characters specified within the param.
  704. func excludesAll(fl FieldLevel) bool {
  705. return !containsAny(fl)
  706. }
  707. // excludes is the validation function for validating that the field's value does not contain the text specified within the param.
  708. func excludes(fl FieldLevel) bool {
  709. return !contains(fl)
  710. }
  711. // containsRune is the validation function for validating that the field's value contains the rune specified within the param.
  712. func containsRune(fl FieldLevel) bool {
  713. r, _ := utf8.DecodeRuneInString(fl.Param())
  714. return strings.ContainsRune(fl.Field().String(), r)
  715. }
  716. // containsAny is the validation function for validating that the field's value contains any of the characters specified within the param.
  717. func containsAny(fl FieldLevel) bool {
  718. return strings.ContainsAny(fl.Field().String(), fl.Param())
  719. }
  720. // contains is the validation function for validating that the field's value contains the text specified within the param.
  721. func contains(fl FieldLevel) bool {
  722. return strings.Contains(fl.Field().String(), fl.Param())
  723. }
  724. // startsWith is the validation function for validating that the field's value starts with the text specified within the param.
  725. func startsWith(fl FieldLevel) bool {
  726. return strings.HasPrefix(fl.Field().String(), fl.Param())
  727. }
  728. // endsWith is the validation function for validating that the field's value ends with the text specified within the param.
  729. func endsWith(fl FieldLevel) bool {
  730. return strings.HasSuffix(fl.Field().String(), fl.Param())
  731. }
  732. // startsNotWith is the validation function for validating that the field's value does not start with the text specified within the param.
  733. func startsNotWith(fl FieldLevel) bool {
  734. return !startsWith(fl)
  735. }
  736. // endsNotWith is the validation function for validating that the field's value does not end with the text specified within the param.
  737. func endsNotWith(fl FieldLevel) bool {
  738. return !endsWith(fl)
  739. }
  740. // fieldContains is the validation function for validating if the current field's value contains the field specified by the param's value.
  741. func fieldContains(fl FieldLevel) bool {
  742. field := fl.Field()
  743. currentField, _, ok := fl.GetStructFieldOK()
  744. if !ok {
  745. return false
  746. }
  747. return strings.Contains(field.String(), currentField.String())
  748. }
  749. // fieldExcludes is the validation function for validating if the current field's value excludes the field specified by the param's value.
  750. func fieldExcludes(fl FieldLevel) bool {
  751. field := fl.Field()
  752. currentField, _, ok := fl.GetStructFieldOK()
  753. if !ok {
  754. return true
  755. }
  756. return !strings.Contains(field.String(), currentField.String())
  757. }
  758. // isNeField is the validation function for validating if the current field's value is not equal to the field specified by the param's value.
  759. func isNeField(fl FieldLevel) bool {
  760. field := fl.Field()
  761. kind := field.Kind()
  762. currentField, currentKind, ok := fl.GetStructFieldOK()
  763. if !ok || currentKind != kind {
  764. return true
  765. }
  766. switch kind {
  767. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  768. return field.Int() != currentField.Int()
  769. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  770. return field.Uint() != currentField.Uint()
  771. case reflect.Float32, reflect.Float64:
  772. return field.Float() != currentField.Float()
  773. case reflect.Slice, reflect.Map, reflect.Array:
  774. return int64(field.Len()) != int64(currentField.Len())
  775. case reflect.Bool:
  776. return field.Bool() != currentField.Bool()
  777. case reflect.Struct:
  778. fieldType := field.Type()
  779. if fieldType.ConvertibleTo(timeType) && currentField.Type().ConvertibleTo(timeType) {
  780. t := currentField.Interface().(time.Time)
  781. fieldTime := field.Interface().(time.Time)
  782. return !fieldTime.Equal(t)
  783. }
  784. // Not Same underlying type i.e. struct and time
  785. if fieldType != currentField.Type() {
  786. return true
  787. }
  788. }
  789. // default reflect.String:
  790. return field.String() != currentField.String()
  791. }
  792. // isNe is the validation function for validating that the field's value does not equal the provided param value.
  793. func isNe(fl FieldLevel) bool {
  794. return !isEq(fl)
  795. }
  796. // isNeIgnoreCase is the validation function for validating that the field's string value does not equal the
  797. // provided param value. The comparison is case-insensitive
  798. func isNeIgnoreCase(fl FieldLevel) bool {
  799. return !isEqIgnoreCase(fl)
  800. }
  801. // isLteCrossStructField is the validation function for validating if the current field's value is less than or equal to the field, within a separate struct, specified by the param's value.
  802. func isLteCrossStructField(fl FieldLevel) bool {
  803. field := fl.Field()
  804. kind := field.Kind()
  805. topField, topKind, ok := fl.GetStructFieldOK()
  806. if !ok || topKind != kind {
  807. return false
  808. }
  809. switch kind {
  810. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  811. return field.Int() <= topField.Int()
  812. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  813. return field.Uint() <= topField.Uint()
  814. case reflect.Float32, reflect.Float64:
  815. return field.Float() <= topField.Float()
  816. case reflect.Slice, reflect.Map, reflect.Array:
  817. return int64(field.Len()) <= int64(topField.Len())
  818. case reflect.Struct:
  819. fieldType := field.Type()
  820. if fieldType.ConvertibleTo(timeType) && topField.Type().ConvertibleTo(timeType) {
  821. fieldTime := field.Convert(timeType).Interface().(time.Time)
  822. topTime := topField.Convert(timeType).Interface().(time.Time)
  823. return fieldTime.Before(topTime) || fieldTime.Equal(topTime)
  824. }
  825. // Not Same underlying type i.e. struct and time
  826. if fieldType != topField.Type() {
  827. return false
  828. }
  829. }
  830. // default reflect.String:
  831. return field.String() <= topField.String()
  832. }
  833. // isLtCrossStructField is the validation function for validating if the current field's value is less than the field, within a separate struct, specified by the param's value.
  834. // NOTE: This is exposed for use within your own custom functions and not intended to be called directly.
  835. func isLtCrossStructField(fl FieldLevel) bool {
  836. field := fl.Field()
  837. kind := field.Kind()
  838. topField, topKind, ok := fl.GetStructFieldOK()
  839. if !ok || topKind != kind {
  840. return false
  841. }
  842. switch kind {
  843. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  844. return field.Int() < topField.Int()
  845. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  846. return field.Uint() < topField.Uint()
  847. case reflect.Float32, reflect.Float64:
  848. return field.Float() < topField.Float()
  849. case reflect.Slice, reflect.Map, reflect.Array:
  850. return int64(field.Len()) < int64(topField.Len())
  851. case reflect.Struct:
  852. fieldType := field.Type()
  853. if fieldType.ConvertibleTo(timeType) && topField.Type().ConvertibleTo(timeType) {
  854. fieldTime := field.Convert(timeType).Interface().(time.Time)
  855. topTime := topField.Convert(timeType).Interface().(time.Time)
  856. return fieldTime.Before(topTime)
  857. }
  858. // Not Same underlying type i.e. struct and time
  859. if fieldType != topField.Type() {
  860. return false
  861. }
  862. }
  863. // default reflect.String:
  864. return field.String() < topField.String()
  865. }
  866. // isGteCrossStructField is the validation function for validating if the current field's value is greater than or equal to the field, within a separate struct, specified by the param's value.
  867. func isGteCrossStructField(fl FieldLevel) bool {
  868. field := fl.Field()
  869. kind := field.Kind()
  870. topField, topKind, ok := fl.GetStructFieldOK()
  871. if !ok || topKind != kind {
  872. return false
  873. }
  874. switch kind {
  875. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  876. return field.Int() >= topField.Int()
  877. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  878. return field.Uint() >= topField.Uint()
  879. case reflect.Float32, reflect.Float64:
  880. return field.Float() >= topField.Float()
  881. case reflect.Slice, reflect.Map, reflect.Array:
  882. return int64(field.Len()) >= int64(topField.Len())
  883. case reflect.Struct:
  884. fieldType := field.Type()
  885. if fieldType.ConvertibleTo(timeType) && topField.Type().ConvertibleTo(timeType) {
  886. fieldTime := field.Convert(timeType).Interface().(time.Time)
  887. topTime := topField.Convert(timeType).Interface().(time.Time)
  888. return fieldTime.After(topTime) || fieldTime.Equal(topTime)
  889. }
  890. // Not Same underlying type i.e. struct and time
  891. if fieldType != topField.Type() {
  892. return false
  893. }
  894. }
  895. // default reflect.String:
  896. return field.String() >= topField.String()
  897. }
  898. // isGtCrossStructField is the validation function for validating if the current field's value is greater than the field, within a separate struct, specified by the param's value.
  899. func isGtCrossStructField(fl FieldLevel) bool {
  900. field := fl.Field()
  901. kind := field.Kind()
  902. topField, topKind, ok := fl.GetStructFieldOK()
  903. if !ok || topKind != kind {
  904. return false
  905. }
  906. switch kind {
  907. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  908. return field.Int() > topField.Int()
  909. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  910. return field.Uint() > topField.Uint()
  911. case reflect.Float32, reflect.Float64:
  912. return field.Float() > topField.Float()
  913. case reflect.Slice, reflect.Map, reflect.Array:
  914. return int64(field.Len()) > int64(topField.Len())
  915. case reflect.Struct:
  916. fieldType := field.Type()
  917. if fieldType.ConvertibleTo(timeType) && topField.Type().ConvertibleTo(timeType) {
  918. fieldTime := field.Convert(timeType).Interface().(time.Time)
  919. topTime := topField.Convert(timeType).Interface().(time.Time)
  920. return fieldTime.After(topTime)
  921. }
  922. // Not Same underlying type i.e. struct and time
  923. if fieldType != topField.Type() {
  924. return false
  925. }
  926. }
  927. // default reflect.String:
  928. return field.String() > topField.String()
  929. }
  930. // isNeCrossStructField is the validation function for validating that the current field's value is not equal to the field, within a separate struct, specified by the param's value.
  931. func isNeCrossStructField(fl FieldLevel) bool {
  932. field := fl.Field()
  933. kind := field.Kind()
  934. topField, currentKind, ok := fl.GetStructFieldOK()
  935. if !ok || currentKind != kind {
  936. return true
  937. }
  938. switch kind {
  939. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  940. return topField.Int() != field.Int()
  941. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  942. return topField.Uint() != field.Uint()
  943. case reflect.Float32, reflect.Float64:
  944. return topField.Float() != field.Float()
  945. case reflect.Slice, reflect.Map, reflect.Array:
  946. return int64(topField.Len()) != int64(field.Len())
  947. case reflect.Bool:
  948. return topField.Bool() != field.Bool()
  949. case reflect.Struct:
  950. fieldType := field.Type()
  951. if fieldType.ConvertibleTo(timeType) && topField.Type().ConvertibleTo(timeType) {
  952. t := field.Convert(timeType).Interface().(time.Time)
  953. fieldTime := topField.Convert(timeType).Interface().(time.Time)
  954. return !fieldTime.Equal(t)
  955. }
  956. // Not Same underlying type i.e. struct and time
  957. if fieldType != topField.Type() {
  958. return true
  959. }
  960. }
  961. // default reflect.String:
  962. return topField.String() != field.String()
  963. }
  964. // isEqCrossStructField is the validation function for validating that the current field's value is equal to the field, within a separate struct, specified by the param's value.
  965. func isEqCrossStructField(fl FieldLevel) bool {
  966. field := fl.Field()
  967. kind := field.Kind()
  968. topField, topKind, ok := fl.GetStructFieldOK()
  969. if !ok || topKind != kind {
  970. return false
  971. }
  972. switch kind {
  973. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  974. return topField.Int() == field.Int()
  975. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  976. return topField.Uint() == field.Uint()
  977. case reflect.Float32, reflect.Float64:
  978. return topField.Float() == field.Float()
  979. case reflect.Slice, reflect.Map, reflect.Array:
  980. return int64(topField.Len()) == int64(field.Len())
  981. case reflect.Bool:
  982. return topField.Bool() == field.Bool()
  983. case reflect.Struct:
  984. fieldType := field.Type()
  985. if fieldType.ConvertibleTo(timeType) && topField.Type().ConvertibleTo(timeType) {
  986. t := field.Convert(timeType).Interface().(time.Time)
  987. fieldTime := topField.Convert(timeType).Interface().(time.Time)
  988. return fieldTime.Equal(t)
  989. }
  990. // Not Same underlying type i.e. struct and time
  991. if fieldType != topField.Type() {
  992. return false
  993. }
  994. }
  995. // default reflect.String:
  996. return topField.String() == field.String()
  997. }
  998. // isEqField is the validation function for validating if the current field's value is equal to the field specified by the param's value.
  999. func isEqField(fl FieldLevel) bool {
  1000. field := fl.Field()
  1001. kind := field.Kind()
  1002. currentField, currentKind, ok := fl.GetStructFieldOK()
  1003. if !ok || currentKind != kind {
  1004. return false
  1005. }
  1006. switch kind {
  1007. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  1008. return field.Int() == currentField.Int()
  1009. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  1010. return field.Uint() == currentField.Uint()
  1011. case reflect.Float32, reflect.Float64:
  1012. return field.Float() == currentField.Float()
  1013. case reflect.Slice, reflect.Map, reflect.Array:
  1014. return int64(field.Len()) == int64(currentField.Len())
  1015. case reflect.Bool:
  1016. return field.Bool() == currentField.Bool()
  1017. case reflect.Struct:
  1018. fieldType := field.Type()
  1019. if fieldType.ConvertibleTo(timeType) && currentField.Type().ConvertibleTo(timeType) {
  1020. t := currentField.Convert(timeType).Interface().(time.Time)
  1021. fieldTime := field.Convert(timeType).Interface().(time.Time)
  1022. return fieldTime.Equal(t)
  1023. }
  1024. // Not Same underlying type i.e. struct and time
  1025. if fieldType != currentField.Type() {
  1026. return false
  1027. }
  1028. }
  1029. // default reflect.String:
  1030. return field.String() == currentField.String()
  1031. }
  1032. // isEq is the validation function for validating if the current field's value is equal to the param's value.
  1033. func isEq(fl FieldLevel) bool {
  1034. field := fl.Field()
  1035. param := fl.Param()
  1036. switch field.Kind() {
  1037. case reflect.String:
  1038. return field.String() == param
  1039. case reflect.Slice, reflect.Map, reflect.Array:
  1040. p := asInt(param)
  1041. return int64(field.Len()) == p
  1042. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  1043. p := asIntFromType(field.Type(), param)
  1044. return field.Int() == p
  1045. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  1046. p := asUint(param)
  1047. return field.Uint() == p
  1048. case reflect.Float32:
  1049. p := asFloat32(param)
  1050. return field.Float() == p
  1051. case reflect.Float64:
  1052. p := asFloat64(param)
  1053. return field.Float() == p
  1054. case reflect.Bool:
  1055. p := asBool(param)
  1056. return field.Bool() == p
  1057. }
  1058. panic(fmt.Sprintf("Bad field type %T", field.Interface()))
  1059. }
  1060. // isEqIgnoreCase is the validation function for validating if the current field's string value is
  1061. // equal to the param's value.
  1062. // The comparison is case-insensitive.
  1063. func isEqIgnoreCase(fl FieldLevel) bool {
  1064. field := fl.Field()
  1065. param := fl.Param()
  1066. switch field.Kind() {
  1067. case reflect.String:
  1068. return strings.EqualFold(field.String(), param)
  1069. }
  1070. panic(fmt.Sprintf("Bad field type %T", field.Interface()))
  1071. }
  1072. // isPostcodeByIso3166Alpha2 validates by value which is country code in iso 3166 alpha 2
  1073. // example: `postcode_iso3166_alpha2=US`
  1074. func isPostcodeByIso3166Alpha2(fl FieldLevel) bool {
  1075. field := fl.Field()
  1076. param := fl.Param()
  1077. reg, found := postCodeRegexDict[param]
  1078. if !found {
  1079. return false
  1080. }
  1081. return reg.MatchString(field.String())
  1082. }
  1083. // isPostcodeByIso3166Alpha2Field validates by field which represents for a value of country code in iso 3166 alpha 2
  1084. // example: `postcode_iso3166_alpha2_field=CountryCode`
  1085. func isPostcodeByIso3166Alpha2Field(fl FieldLevel) bool {
  1086. field := fl.Field()
  1087. params := parseOneOfParam2(fl.Param())
  1088. if len(params) != 1 {
  1089. return false
  1090. }
  1091. currentField, kind, _, found := fl.GetStructFieldOKAdvanced2(fl.Parent(), params[0])
  1092. if !found {
  1093. return false
  1094. }
  1095. if kind != reflect.String {
  1096. panic(fmt.Sprintf("Bad field type %T", currentField.Interface()))
  1097. }
  1098. reg, found := postCodeRegexDict[currentField.String()]
  1099. if !found {
  1100. return false
  1101. }
  1102. return reg.MatchString(field.String())
  1103. }
  1104. // isBase32 is the validation function for validating if the current field's value is a valid base 32.
  1105. func isBase32(fl FieldLevel) bool {
  1106. return base32Regex.MatchString(fl.Field().String())
  1107. }
  1108. // isBase64 is the validation function for validating if the current field's value is a valid base 64.
  1109. func isBase64(fl FieldLevel) bool {
  1110. return base64Regex.MatchString(fl.Field().String())
  1111. }
  1112. // isBase64URL is the validation function for validating if the current field's value is a valid base64 URL safe string.
  1113. func isBase64URL(fl FieldLevel) bool {
  1114. return base64URLRegex.MatchString(fl.Field().String())
  1115. }
  1116. // isBase64RawURL is the validation function for validating if the current field's value is a valid base64 URL safe string without '=' padding.
  1117. func isBase64RawURL(fl FieldLevel) bool {
  1118. return base64RawURLRegex.MatchString(fl.Field().String())
  1119. }
  1120. // isURI is the validation function for validating if the current field's value is a valid URI.
  1121. func isURI(fl FieldLevel) bool {
  1122. field := fl.Field()
  1123. switch field.Kind() {
  1124. case reflect.String:
  1125. s := field.String()
  1126. // checks needed as of Go 1.6 because of change https://github.com/golang/go/commit/617c93ce740c3c3cc28cdd1a0d712be183d0b328#diff-6c2d018290e298803c0c9419d8739885L195
  1127. // emulate browser and strip the '#' suffix prior to validation. see issue-#237
  1128. if i := strings.Index(s, "#"); i > -1 {
  1129. s = s[:i]
  1130. }
  1131. if len(s) == 0 {
  1132. return false
  1133. }
  1134. _, err := url.ParseRequestURI(s)
  1135. return err == nil
  1136. }
  1137. panic(fmt.Sprintf("Bad field type %T", field.Interface()))
  1138. }
  1139. // isFileURL is the helper function for validating if the `path` valid file URL as per RFC8089
  1140. func isFileURL(path string) bool {
  1141. if !strings.HasPrefix(path, "file:/") {
  1142. return false
  1143. }
  1144. _, err := url.ParseRequestURI(path)
  1145. return err == nil
  1146. }
  1147. // isURL is the validation function for validating if the current field's value is a valid URL.
  1148. func isURL(fl FieldLevel) bool {
  1149. field := fl.Field()
  1150. switch field.Kind() {
  1151. case reflect.String:
  1152. s := strings.ToLower(field.String())
  1153. if len(s) == 0 {
  1154. return false
  1155. }
  1156. if isFileURL(s) {
  1157. return true
  1158. }
  1159. url, err := url.Parse(s)
  1160. if err != nil || url.Scheme == "" {
  1161. return false
  1162. }
  1163. if url.Host == "" && url.Fragment == "" && url.Opaque == "" {
  1164. return false
  1165. }
  1166. return true
  1167. }
  1168. panic(fmt.Sprintf("Bad field type %T", field.Interface()))
  1169. }
  1170. // isHttpURL is the validation function for validating if the current field's value is a valid HTTP(s) URL.
  1171. func isHttpURL(fl FieldLevel) bool {
  1172. if !isURL(fl) {
  1173. return false
  1174. }
  1175. field := fl.Field()
  1176. switch field.Kind() {
  1177. case reflect.String:
  1178. s := strings.ToLower(field.String())
  1179. url, err := url.Parse(s)
  1180. if err != nil || url.Host == "" {
  1181. return false
  1182. }
  1183. return url.Scheme == "http" || url.Scheme == "https"
  1184. }
  1185. panic(fmt.Sprintf("Bad field type %T", field.Interface()))
  1186. }
  1187. // isUrnRFC2141 is the validation function for validating if the current field's value is a valid URN as per RFC 2141.
  1188. func isUrnRFC2141(fl FieldLevel) bool {
  1189. field := fl.Field()
  1190. switch field.Kind() {
  1191. case reflect.String:
  1192. str := field.String()
  1193. _, match := urn.Parse([]byte(str))
  1194. return match
  1195. }
  1196. panic(fmt.Sprintf("Bad field type %T", field.Interface()))
  1197. }
  1198. // isFile is the validation function for validating if the current field's value is a valid existing file path.
  1199. func isFile(fl FieldLevel) bool {
  1200. field := fl.Field()
  1201. switch field.Kind() {
  1202. case reflect.String:
  1203. fileInfo, err := os.Stat(field.String())
  1204. if err != nil {
  1205. return false
  1206. }
  1207. return !fileInfo.IsDir()
  1208. }
  1209. panic(fmt.Sprintf("Bad field type %T", field.Interface()))
  1210. }
  1211. // isImage is the validation function for validating if the current field's value contains the path to a valid image file
  1212. func isImage(fl FieldLevel) bool {
  1213. mimetypes := map[string]bool{
  1214. "image/bmp": true,
  1215. "image/cis-cod": true,
  1216. "image/gif": true,
  1217. "image/ief": true,
  1218. "image/jpeg": true,
  1219. "image/jp2": true,
  1220. "image/jpx": true,
  1221. "image/jpm": true,
  1222. "image/pipeg": true,
  1223. "image/png": true,
  1224. "image/svg+xml": true,
  1225. "image/tiff": true,
  1226. "image/webp": true,
  1227. "image/x-cmu-raster": true,
  1228. "image/x-cmx": true,
  1229. "image/x-icon": true,
  1230. "image/x-portable-anymap": true,
  1231. "image/x-portable-bitmap": true,
  1232. "image/x-portable-graymap": true,
  1233. "image/x-portable-pixmap": true,
  1234. "image/x-rgb": true,
  1235. "image/x-xbitmap": true,
  1236. "image/x-xpixmap": true,
  1237. "image/x-xwindowdump": true,
  1238. }
  1239. field := fl.Field()
  1240. switch field.Kind() {
  1241. case reflect.String:
  1242. filePath := field.String()
  1243. fileInfo, err := os.Stat(filePath)
  1244. if err != nil {
  1245. return false
  1246. }
  1247. if fileInfo.IsDir() {
  1248. return false
  1249. }
  1250. file, err := os.Open(filePath)
  1251. if err != nil {
  1252. return false
  1253. }
  1254. defer file.Close()
  1255. mime, err := mimetype.DetectReader(file)
  1256. if err != nil {
  1257. return false
  1258. }
  1259. if _, ok := mimetypes[mime.String()]; ok {
  1260. return true
  1261. }
  1262. }
  1263. return false
  1264. }
  1265. // isFilePath is the validation function for validating if the current field's value is a valid file path.
  1266. func isFilePath(fl FieldLevel) bool {
  1267. var exists bool
  1268. var err error
  1269. field := fl.Field()
  1270. // Not valid if it is a directory.
  1271. if isDir(fl) {
  1272. return false
  1273. }
  1274. // If it exists, it obviously is valid.
  1275. // This is done first to avoid code duplication and unnecessary additional logic.
  1276. if exists = isFile(fl); exists {
  1277. return true
  1278. }
  1279. // It does not exist but may still be a valid filepath.
  1280. switch field.Kind() {
  1281. case reflect.String:
  1282. // Every OS allows for whitespace, but none
  1283. // let you use a file with no filename (to my knowledge).
  1284. // Unless you're dealing with raw inodes, but I digress.
  1285. if strings.TrimSpace(field.String()) == "" {
  1286. return false
  1287. }
  1288. // We make sure it isn't a directory.
  1289. if strings.HasSuffix(field.String(), string(os.PathSeparator)) {
  1290. return false
  1291. }
  1292. if _, err = os.Stat(field.String()); err != nil {
  1293. switch t := err.(type) {
  1294. case *fs.PathError:
  1295. if t.Err == syscall.EINVAL {
  1296. // It's definitely an invalid character in the filepath.
  1297. return false
  1298. }
  1299. // It could be a permission error, a does-not-exist error, etc.
  1300. // Out-of-scope for this validation, though.
  1301. return true
  1302. default:
  1303. // Something went *seriously* wrong.
  1304. /*
  1305. Per https://pkg.go.dev/os#Stat:
  1306. "If there is an error, it will be of type *PathError."
  1307. */
  1308. panic(err)
  1309. }
  1310. }
  1311. }
  1312. panic(fmt.Sprintf("Bad field type %T", field.Interface()))
  1313. }
  1314. // isE164 is the validation function for validating if the current field's value is a valid e.164 formatted phone number.
  1315. func isE164(fl FieldLevel) bool {
  1316. return e164Regex.MatchString(fl.Field().String())
  1317. }
  1318. // isEmail is the validation function for validating if the current field's value is a valid email address.
  1319. func isEmail(fl FieldLevel) bool {
  1320. return emailRegex.MatchString(fl.Field().String())
  1321. }
  1322. // isHSLA is the validation function for validating if the current field's value is a valid HSLA color.
  1323. func isHSLA(fl FieldLevel) bool {
  1324. return hslaRegex.MatchString(fl.Field().String())
  1325. }
  1326. // isHSL is the validation function for validating if the current field's value is a valid HSL color.
  1327. func isHSL(fl FieldLevel) bool {
  1328. return hslRegex.MatchString(fl.Field().String())
  1329. }
  1330. // isRGBA is the validation function for validating if the current field's value is a valid RGBA color.
  1331. func isRGBA(fl FieldLevel) bool {
  1332. return rgbaRegex.MatchString(fl.Field().String())
  1333. }
  1334. // isRGB is the validation function for validating if the current field's value is a valid RGB color.
  1335. func isRGB(fl FieldLevel) bool {
  1336. return rgbRegex.MatchString(fl.Field().String())
  1337. }
  1338. // isHEXColor is the validation function for validating if the current field's value is a valid HEX color.
  1339. func isHEXColor(fl FieldLevel) bool {
  1340. return hexColorRegex.MatchString(fl.Field().String())
  1341. }
  1342. // isHexadecimal is the validation function for validating if the current field's value is a valid hexadecimal.
  1343. func isHexadecimal(fl FieldLevel) bool {
  1344. return hexadecimalRegex.MatchString(fl.Field().String())
  1345. }
  1346. // isNumber is the validation function for validating if the current field's value is a valid number.
  1347. func isNumber(fl FieldLevel) bool {
  1348. switch fl.Field().Kind() {
  1349. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64:
  1350. return true
  1351. default:
  1352. return numberRegex.MatchString(fl.Field().String())
  1353. }
  1354. }
  1355. // isNumeric is the validation function for validating if the current field's value is a valid numeric value.
  1356. func isNumeric(fl FieldLevel) bool {
  1357. switch fl.Field().Kind() {
  1358. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr, reflect.Float32, reflect.Float64:
  1359. return true
  1360. default:
  1361. return numericRegex.MatchString(fl.Field().String())
  1362. }
  1363. }
  1364. // isAlphanum is the validation function for validating if the current field's value is a valid alphanumeric value.
  1365. func isAlphanum(fl FieldLevel) bool {
  1366. return alphaNumericRegex.MatchString(fl.Field().String())
  1367. }
  1368. // isAlpha is the validation function for validating if the current field's value is a valid alpha value.
  1369. func isAlpha(fl FieldLevel) bool {
  1370. return alphaRegex.MatchString(fl.Field().String())
  1371. }
  1372. // isAlphanumUnicode is the validation function for validating if the current field's value is a valid alphanumeric unicode value.
  1373. func isAlphanumUnicode(fl FieldLevel) bool {
  1374. return alphaUnicodeNumericRegex.MatchString(fl.Field().String())
  1375. }
  1376. // isAlphaUnicode is the validation function for validating if the current field's value is a valid alpha unicode value.
  1377. func isAlphaUnicode(fl FieldLevel) bool {
  1378. return alphaUnicodeRegex.MatchString(fl.Field().String())
  1379. }
  1380. // isBoolean is the validation function for validating if the current field's value is a valid boolean value or can be safely converted to a boolean value.
  1381. func isBoolean(fl FieldLevel) bool {
  1382. switch fl.Field().Kind() {
  1383. case reflect.Bool:
  1384. return true
  1385. default:
  1386. _, err := strconv.ParseBool(fl.Field().String())
  1387. return err == nil
  1388. }
  1389. }
  1390. // isDefault is the opposite of required aka hasValue
  1391. func isDefault(fl FieldLevel) bool {
  1392. return !hasValue(fl)
  1393. }
  1394. // hasValue is the validation function for validating if the current field's value is not the default static value.
  1395. func hasValue(fl FieldLevel) bool {
  1396. field := fl.Field()
  1397. switch field.Kind() {
  1398. case reflect.Slice, reflect.Map, reflect.Ptr, reflect.Interface, reflect.Chan, reflect.Func:
  1399. return !field.IsNil()
  1400. default:
  1401. if fl.(*validate).fldIsPointer && field.Interface() != nil {
  1402. return true
  1403. }
  1404. return field.IsValid() && !field.IsZero()
  1405. }
  1406. }
  1407. // requireCheckFieldKind is a func for check field kind
  1408. func requireCheckFieldKind(fl FieldLevel, param string, defaultNotFoundValue bool) bool {
  1409. field := fl.Field()
  1410. kind := field.Kind()
  1411. var nullable, found bool
  1412. if len(param) > 0 {
  1413. field, kind, nullable, found = fl.GetStructFieldOKAdvanced2(fl.Parent(), param)
  1414. if !found {
  1415. return defaultNotFoundValue
  1416. }
  1417. }
  1418. switch kind {
  1419. case reflect.Invalid:
  1420. return defaultNotFoundValue
  1421. case reflect.Slice, reflect.Map, reflect.Ptr, reflect.Interface, reflect.Chan, reflect.Func:
  1422. return field.IsNil()
  1423. default:
  1424. if nullable && field.Interface() != nil {
  1425. return false
  1426. }
  1427. return field.IsValid() && field.IsZero()
  1428. }
  1429. }
  1430. // requireCheckFieldValue is a func for check field value
  1431. func requireCheckFieldValue(
  1432. fl FieldLevel, param string, value string, defaultNotFoundValue bool,
  1433. ) bool {
  1434. field, kind, _, found := fl.GetStructFieldOKAdvanced2(fl.Parent(), param)
  1435. if !found {
  1436. return defaultNotFoundValue
  1437. }
  1438. switch kind {
  1439. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  1440. return field.Int() == asInt(value)
  1441. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  1442. return field.Uint() == asUint(value)
  1443. case reflect.Float32:
  1444. return field.Float() == asFloat32(value)
  1445. case reflect.Float64:
  1446. return field.Float() == asFloat64(value)
  1447. case reflect.Slice, reflect.Map, reflect.Array:
  1448. return int64(field.Len()) == asInt(value)
  1449. case reflect.Bool:
  1450. return field.Bool() == asBool(value)
  1451. }
  1452. // default reflect.String:
  1453. return field.String() == value
  1454. }
  1455. // requiredIf is the validation function
  1456. // The field under validation must be present and not empty only if all the other specified fields are equal to the value following with the specified field.
  1457. func requiredIf(fl FieldLevel) bool {
  1458. params := parseOneOfParam2(fl.Param())
  1459. if len(params)%2 != 0 {
  1460. panic(fmt.Sprintf("Bad param number for required_if %s", fl.FieldName()))
  1461. }
  1462. for i := 0; i < len(params); i += 2 {
  1463. if !requireCheckFieldValue(fl, params[i], params[i+1], false) {
  1464. return true
  1465. }
  1466. }
  1467. return hasValue(fl)
  1468. }
  1469. // excludedIf is the validation function
  1470. // The field under validation must not be present or is empty only if all the other specified fields are equal to the value following with the specified field.
  1471. func excludedIf(fl FieldLevel) bool {
  1472. params := parseOneOfParam2(fl.Param())
  1473. if len(params)%2 != 0 {
  1474. panic(fmt.Sprintf("Bad param number for excluded_if %s", fl.FieldName()))
  1475. }
  1476. for i := 0; i < len(params); i += 2 {
  1477. if !requireCheckFieldValue(fl, params[i], params[i+1], false) {
  1478. return true
  1479. }
  1480. }
  1481. return !hasValue(fl)
  1482. }
  1483. // requiredUnless is the validation function
  1484. // The field under validation must be present and not empty only unless all the other specified fields are equal to the value following with the specified field.
  1485. func requiredUnless(fl FieldLevel) bool {
  1486. params := parseOneOfParam2(fl.Param())
  1487. if len(params)%2 != 0 {
  1488. panic(fmt.Sprintf("Bad param number for required_unless %s", fl.FieldName()))
  1489. }
  1490. for i := 0; i < len(params); i += 2 {
  1491. if requireCheckFieldValue(fl, params[i], params[i+1], false) {
  1492. return true
  1493. }
  1494. }
  1495. return hasValue(fl)
  1496. }
  1497. // skipUnless is the validation function
  1498. // The field under validation must be present and not empty only unless all the other specified fields are equal to the value following with the specified field.
  1499. func skipUnless(fl FieldLevel) bool {
  1500. params := parseOneOfParam2(fl.Param())
  1501. if len(params)%2 != 0 {
  1502. panic(fmt.Sprintf("Bad param number for skip_unless %s", fl.FieldName()))
  1503. }
  1504. for i := 0; i < len(params); i += 2 {
  1505. if !requireCheckFieldValue(fl, params[i], params[i+1], false) {
  1506. return true
  1507. }
  1508. }
  1509. return hasValue(fl)
  1510. }
  1511. // excludedUnless is the validation function
  1512. // The field under validation must not be present or is empty unless all the other specified fields are equal to the value following with the specified field.
  1513. func excludedUnless(fl FieldLevel) bool {
  1514. params := parseOneOfParam2(fl.Param())
  1515. if len(params)%2 != 0 {
  1516. panic(fmt.Sprintf("Bad param number for excluded_unless %s", fl.FieldName()))
  1517. }
  1518. for i := 0; i < len(params); i += 2 {
  1519. if !requireCheckFieldValue(fl, params[i], params[i+1], false) {
  1520. return !hasValue(fl)
  1521. }
  1522. }
  1523. return true
  1524. }
  1525. // excludedWith is the validation function
  1526. // The field under validation must not be present or is empty if any of the other specified fields are present.
  1527. func excludedWith(fl FieldLevel) bool {
  1528. params := parseOneOfParam2(fl.Param())
  1529. for _, param := range params {
  1530. if !requireCheckFieldKind(fl, param, true) {
  1531. return !hasValue(fl)
  1532. }
  1533. }
  1534. return true
  1535. }
  1536. // requiredWith is the validation function
  1537. // The field under validation must be present and not empty only if any of the other specified fields are present.
  1538. func requiredWith(fl FieldLevel) bool {
  1539. params := parseOneOfParam2(fl.Param())
  1540. for _, param := range params {
  1541. if !requireCheckFieldKind(fl, param, true) {
  1542. return hasValue(fl)
  1543. }
  1544. }
  1545. return true
  1546. }
  1547. // excludedWithAll is the validation function
  1548. // The field under validation must not be present or is empty if all of the other specified fields are present.
  1549. func excludedWithAll(fl FieldLevel) bool {
  1550. params := parseOneOfParam2(fl.Param())
  1551. for _, param := range params {
  1552. if requireCheckFieldKind(fl, param, true) {
  1553. return true
  1554. }
  1555. }
  1556. return !hasValue(fl)
  1557. }
  1558. // requiredWithAll is the validation function
  1559. // The field under validation must be present and not empty only if all of the other specified fields are present.
  1560. func requiredWithAll(fl FieldLevel) bool {
  1561. params := parseOneOfParam2(fl.Param())
  1562. for _, param := range params {
  1563. if requireCheckFieldKind(fl, param, true) {
  1564. return true
  1565. }
  1566. }
  1567. return hasValue(fl)
  1568. }
  1569. // excludedWithout is the validation function
  1570. // The field under validation must not be present or is empty when any of the other specified fields are not present.
  1571. func excludedWithout(fl FieldLevel) bool {
  1572. if requireCheckFieldKind(fl, strings.TrimSpace(fl.Param()), true) {
  1573. return !hasValue(fl)
  1574. }
  1575. return true
  1576. }
  1577. // requiredWithout is the validation function
  1578. // The field under validation must be present and not empty only when any of the other specified fields are not present.
  1579. func requiredWithout(fl FieldLevel) bool {
  1580. if requireCheckFieldKind(fl, strings.TrimSpace(fl.Param()), true) {
  1581. return hasValue(fl)
  1582. }
  1583. return true
  1584. }
  1585. // excludedWithoutAll is the validation function
  1586. // The field under validation must not be present or is empty when all of the other specified fields are not present.
  1587. func excludedWithoutAll(fl FieldLevel) bool {
  1588. params := parseOneOfParam2(fl.Param())
  1589. for _, param := range params {
  1590. if !requireCheckFieldKind(fl, param, true) {
  1591. return true
  1592. }
  1593. }
  1594. return !hasValue(fl)
  1595. }
  1596. // requiredWithoutAll is the validation function
  1597. // The field under validation must be present and not empty only when all of the other specified fields are not present.
  1598. func requiredWithoutAll(fl FieldLevel) bool {
  1599. params := parseOneOfParam2(fl.Param())
  1600. for _, param := range params {
  1601. if !requireCheckFieldKind(fl, param, true) {
  1602. return true
  1603. }
  1604. }
  1605. return hasValue(fl)
  1606. }
  1607. // isGteField is the validation function for validating if the current field's value is greater than or equal to the field specified by the param's value.
  1608. func isGteField(fl FieldLevel) bool {
  1609. field := fl.Field()
  1610. kind := field.Kind()
  1611. currentField, currentKind, ok := fl.GetStructFieldOK()
  1612. if !ok || currentKind != kind {
  1613. return false
  1614. }
  1615. switch kind {
  1616. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  1617. return field.Int() >= currentField.Int()
  1618. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  1619. return field.Uint() >= currentField.Uint()
  1620. case reflect.Float32, reflect.Float64:
  1621. return field.Float() >= currentField.Float()
  1622. case reflect.Struct:
  1623. fieldType := field.Type()
  1624. if fieldType.ConvertibleTo(timeType) && currentField.Type().ConvertibleTo(timeType) {
  1625. t := currentField.Convert(timeType).Interface().(time.Time)
  1626. fieldTime := field.Convert(timeType).Interface().(time.Time)
  1627. return fieldTime.After(t) || fieldTime.Equal(t)
  1628. }
  1629. // Not Same underlying type i.e. struct and time
  1630. if fieldType != currentField.Type() {
  1631. return false
  1632. }
  1633. }
  1634. // default reflect.String
  1635. return len(field.String()) >= len(currentField.String())
  1636. }
  1637. // isGtField is the validation function for validating if the current field's value is greater than the field specified by the param's value.
  1638. func isGtField(fl FieldLevel) bool {
  1639. field := fl.Field()
  1640. kind := field.Kind()
  1641. currentField, currentKind, ok := fl.GetStructFieldOK()
  1642. if !ok || currentKind != kind {
  1643. return false
  1644. }
  1645. switch kind {
  1646. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  1647. return field.Int() > currentField.Int()
  1648. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  1649. return field.Uint() > currentField.Uint()
  1650. case reflect.Float32, reflect.Float64:
  1651. return field.Float() > currentField.Float()
  1652. case reflect.Struct:
  1653. fieldType := field.Type()
  1654. if fieldType.ConvertibleTo(timeType) && currentField.Type().ConvertibleTo(timeType) {
  1655. t := currentField.Convert(timeType).Interface().(time.Time)
  1656. fieldTime := field.Convert(timeType).Interface().(time.Time)
  1657. return fieldTime.After(t)
  1658. }
  1659. // Not Same underlying type i.e. struct and time
  1660. if fieldType != currentField.Type() {
  1661. return false
  1662. }
  1663. }
  1664. // default reflect.String
  1665. return len(field.String()) > len(currentField.String())
  1666. }
  1667. // isGte is the validation function for validating if the current field's value is greater than or equal to the param's value.
  1668. func isGte(fl FieldLevel) bool {
  1669. field := fl.Field()
  1670. param := fl.Param()
  1671. switch field.Kind() {
  1672. case reflect.String:
  1673. p := asInt(param)
  1674. return int64(utf8.RuneCountInString(field.String())) >= p
  1675. case reflect.Slice, reflect.Map, reflect.Array:
  1676. p := asInt(param)
  1677. return int64(field.Len()) >= p
  1678. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  1679. p := asIntFromType(field.Type(), param)
  1680. return field.Int() >= p
  1681. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  1682. p := asUint(param)
  1683. return field.Uint() >= p
  1684. case reflect.Float32:
  1685. p := asFloat32(param)
  1686. return field.Float() >= p
  1687. case reflect.Float64:
  1688. p := asFloat64(param)
  1689. return field.Float() >= p
  1690. case reflect.Struct:
  1691. if field.Type().ConvertibleTo(timeType) {
  1692. now := time.Now().UTC()
  1693. t := field.Convert(timeType).Interface().(time.Time)
  1694. return t.After(now) || t.Equal(now)
  1695. }
  1696. }
  1697. panic(fmt.Sprintf("Bad field type %T", field.Interface()))
  1698. }
  1699. // isGt is the validation function for validating if the current field's value is greater than the param's value.
  1700. func isGt(fl FieldLevel) bool {
  1701. field := fl.Field()
  1702. param := fl.Param()
  1703. switch field.Kind() {
  1704. case reflect.String:
  1705. p := asInt(param)
  1706. return int64(utf8.RuneCountInString(field.String())) > p
  1707. case reflect.Slice, reflect.Map, reflect.Array:
  1708. p := asInt(param)
  1709. return int64(field.Len()) > p
  1710. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  1711. p := asIntFromType(field.Type(), param)
  1712. return field.Int() > p
  1713. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  1714. p := asUint(param)
  1715. return field.Uint() > p
  1716. case reflect.Float32:
  1717. p := asFloat32(param)
  1718. return field.Float() > p
  1719. case reflect.Float64:
  1720. p := asFloat64(param)
  1721. return field.Float() > p
  1722. case reflect.Struct:
  1723. if field.Type().ConvertibleTo(timeType) {
  1724. return field.Convert(timeType).Interface().(time.Time).After(time.Now().UTC())
  1725. }
  1726. }
  1727. panic(fmt.Sprintf("Bad field type %T", field.Interface()))
  1728. }
  1729. // hasLengthOf is the validation function for validating if the current field's value is equal to the param's value.
  1730. func hasLengthOf(fl FieldLevel) bool {
  1731. field := fl.Field()
  1732. param := fl.Param()
  1733. switch field.Kind() {
  1734. case reflect.String:
  1735. p := asInt(param)
  1736. return int64(utf8.RuneCountInString(field.String())) == p
  1737. case reflect.Slice, reflect.Map, reflect.Array:
  1738. p := asInt(param)
  1739. return int64(field.Len()) == p
  1740. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  1741. p := asIntFromType(field.Type(), param)
  1742. return field.Int() == p
  1743. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  1744. p := asUint(param)
  1745. return field.Uint() == p
  1746. case reflect.Float32:
  1747. p := asFloat32(param)
  1748. return field.Float() == p
  1749. case reflect.Float64:
  1750. p := asFloat64(param)
  1751. return field.Float() == p
  1752. }
  1753. panic(fmt.Sprintf("Bad field type %T", field.Interface()))
  1754. }
  1755. // hasMinOf is the validation function for validating if the current field's value is greater than or equal to the param's value.
  1756. func hasMinOf(fl FieldLevel) bool {
  1757. return isGte(fl)
  1758. }
  1759. // isLteField is the validation function for validating if the current field's value is less than or equal to the field specified by the param's value.
  1760. func isLteField(fl FieldLevel) bool {
  1761. field := fl.Field()
  1762. kind := field.Kind()
  1763. currentField, currentKind, ok := fl.GetStructFieldOK()
  1764. if !ok || currentKind != kind {
  1765. return false
  1766. }
  1767. switch kind {
  1768. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  1769. return field.Int() <= currentField.Int()
  1770. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  1771. return field.Uint() <= currentField.Uint()
  1772. case reflect.Float32, reflect.Float64:
  1773. return field.Float() <= currentField.Float()
  1774. case reflect.Struct:
  1775. fieldType := field.Type()
  1776. if fieldType.ConvertibleTo(timeType) && currentField.Type().ConvertibleTo(timeType) {
  1777. t := currentField.Convert(timeType).Interface().(time.Time)
  1778. fieldTime := field.Convert(timeType).Interface().(time.Time)
  1779. return fieldTime.Before(t) || fieldTime.Equal(t)
  1780. }
  1781. // Not Same underlying type i.e. struct and time
  1782. if fieldType != currentField.Type() {
  1783. return false
  1784. }
  1785. }
  1786. // default reflect.String
  1787. return len(field.String()) <= len(currentField.String())
  1788. }
  1789. // isLtField is the validation function for validating if the current field's value is less than the field specified by the param's value.
  1790. func isLtField(fl FieldLevel) bool {
  1791. field := fl.Field()
  1792. kind := field.Kind()
  1793. currentField, currentKind, ok := fl.GetStructFieldOK()
  1794. if !ok || currentKind != kind {
  1795. return false
  1796. }
  1797. switch kind {
  1798. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  1799. return field.Int() < currentField.Int()
  1800. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  1801. return field.Uint() < currentField.Uint()
  1802. case reflect.Float32, reflect.Float64:
  1803. return field.Float() < currentField.Float()
  1804. case reflect.Struct:
  1805. fieldType := field.Type()
  1806. if fieldType.ConvertibleTo(timeType) && currentField.Type().ConvertibleTo(timeType) {
  1807. t := currentField.Convert(timeType).Interface().(time.Time)
  1808. fieldTime := field.Convert(timeType).Interface().(time.Time)
  1809. return fieldTime.Before(t)
  1810. }
  1811. // Not Same underlying type i.e. struct and time
  1812. if fieldType != currentField.Type() {
  1813. return false
  1814. }
  1815. }
  1816. // default reflect.String
  1817. return len(field.String()) < len(currentField.String())
  1818. }
  1819. // isLte is the validation function for validating if the current field's value is less than or equal to the param's value.
  1820. func isLte(fl FieldLevel) bool {
  1821. field := fl.Field()
  1822. param := fl.Param()
  1823. switch field.Kind() {
  1824. case reflect.String:
  1825. p := asInt(param)
  1826. return int64(utf8.RuneCountInString(field.String())) <= p
  1827. case reflect.Slice, reflect.Map, reflect.Array:
  1828. p := asInt(param)
  1829. return int64(field.Len()) <= p
  1830. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  1831. p := asIntFromType(field.Type(), param)
  1832. return field.Int() <= p
  1833. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  1834. p := asUint(param)
  1835. return field.Uint() <= p
  1836. case reflect.Float32:
  1837. p := asFloat32(param)
  1838. return field.Float() <= p
  1839. case reflect.Float64:
  1840. p := asFloat64(param)
  1841. return field.Float() <= p
  1842. case reflect.Struct:
  1843. if field.Type().ConvertibleTo(timeType) {
  1844. now := time.Now().UTC()
  1845. t := field.Convert(timeType).Interface().(time.Time)
  1846. return t.Before(now) || t.Equal(now)
  1847. }
  1848. }
  1849. panic(fmt.Sprintf("Bad field type %T", field.Interface()))
  1850. }
  1851. // isLt is the validation function for validating if the current field's value is less than the param's value.
  1852. func isLt(fl FieldLevel) bool {
  1853. field := fl.Field()
  1854. param := fl.Param()
  1855. switch field.Kind() {
  1856. case reflect.String:
  1857. p := asInt(param)
  1858. return int64(utf8.RuneCountInString(field.String())) < p
  1859. case reflect.Slice, reflect.Map, reflect.Array:
  1860. p := asInt(param)
  1861. return int64(field.Len()) < p
  1862. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  1863. p := asIntFromType(field.Type(), param)
  1864. return field.Int() < p
  1865. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  1866. p := asUint(param)
  1867. return field.Uint() < p
  1868. case reflect.Float32:
  1869. p := asFloat32(param)
  1870. return field.Float() < p
  1871. case reflect.Float64:
  1872. p := asFloat64(param)
  1873. return field.Float() < p
  1874. case reflect.Struct:
  1875. if field.Type().ConvertibleTo(timeType) {
  1876. return field.Convert(timeType).Interface().(time.Time).Before(time.Now().UTC())
  1877. }
  1878. }
  1879. panic(fmt.Sprintf("Bad field type %T", field.Interface()))
  1880. }
  1881. // hasMaxOf is the validation function for validating if the current field's value is less than or equal to the param's value.
  1882. func hasMaxOf(fl FieldLevel) bool {
  1883. return isLte(fl)
  1884. }
  1885. // isTCP4AddrResolvable is the validation function for validating if the field's value is a resolvable tcp4 address.
  1886. func isTCP4AddrResolvable(fl FieldLevel) bool {
  1887. if !isIP4Addr(fl) {
  1888. return false
  1889. }
  1890. _, err := net.ResolveTCPAddr("tcp4", fl.Field().String())
  1891. return err == nil
  1892. }
  1893. // isTCP6AddrResolvable is the validation function for validating if the field's value is a resolvable tcp6 address.
  1894. func isTCP6AddrResolvable(fl FieldLevel) bool {
  1895. if !isIP6Addr(fl) {
  1896. return false
  1897. }
  1898. _, err := net.ResolveTCPAddr("tcp6", fl.Field().String())
  1899. return err == nil
  1900. }
  1901. // isTCPAddrResolvable is the validation function for validating if the field's value is a resolvable tcp address.
  1902. func isTCPAddrResolvable(fl FieldLevel) bool {
  1903. if !isIP4Addr(fl) && !isIP6Addr(fl) {
  1904. return false
  1905. }
  1906. _, err := net.ResolveTCPAddr("tcp", fl.Field().String())
  1907. return err == nil
  1908. }
  1909. // isUDP4AddrResolvable is the validation function for validating if the field's value is a resolvable udp4 address.
  1910. func isUDP4AddrResolvable(fl FieldLevel) bool {
  1911. if !isIP4Addr(fl) {
  1912. return false
  1913. }
  1914. _, err := net.ResolveUDPAddr("udp4", fl.Field().String())
  1915. return err == nil
  1916. }
  1917. // isUDP6AddrResolvable is the validation function for validating if the field's value is a resolvable udp6 address.
  1918. func isUDP6AddrResolvable(fl FieldLevel) bool {
  1919. if !isIP6Addr(fl) {
  1920. return false
  1921. }
  1922. _, err := net.ResolveUDPAddr("udp6", fl.Field().String())
  1923. return err == nil
  1924. }
  1925. // isUDPAddrResolvable is the validation function for validating if the field's value is a resolvable udp address.
  1926. func isUDPAddrResolvable(fl FieldLevel) bool {
  1927. if !isIP4Addr(fl) && !isIP6Addr(fl) {
  1928. return false
  1929. }
  1930. _, err := net.ResolveUDPAddr("udp", fl.Field().String())
  1931. return err == nil
  1932. }
  1933. // isIP4AddrResolvable is the validation function for validating if the field's value is a resolvable ip4 address.
  1934. func isIP4AddrResolvable(fl FieldLevel) bool {
  1935. if !isIPv4(fl) {
  1936. return false
  1937. }
  1938. _, err := net.ResolveIPAddr("ip4", fl.Field().String())
  1939. return err == nil
  1940. }
  1941. // isIP6AddrResolvable is the validation function for validating if the field's value is a resolvable ip6 address.
  1942. func isIP6AddrResolvable(fl FieldLevel) bool {
  1943. if !isIPv6(fl) {
  1944. return false
  1945. }
  1946. _, err := net.ResolveIPAddr("ip6", fl.Field().String())
  1947. return err == nil
  1948. }
  1949. // isIPAddrResolvable is the validation function for validating if the field's value is a resolvable ip address.
  1950. func isIPAddrResolvable(fl FieldLevel) bool {
  1951. if !isIP(fl) {
  1952. return false
  1953. }
  1954. _, err := net.ResolveIPAddr("ip", fl.Field().String())
  1955. return err == nil
  1956. }
  1957. // isUnixAddrResolvable is the validation function for validating if the field's value is a resolvable unix address.
  1958. func isUnixAddrResolvable(fl FieldLevel) bool {
  1959. _, err := net.ResolveUnixAddr("unix", fl.Field().String())
  1960. return err == nil
  1961. }
  1962. func isIP4Addr(fl FieldLevel) bool {
  1963. val := fl.Field().String()
  1964. if idx := strings.LastIndex(val, ":"); idx != -1 {
  1965. val = val[0:idx]
  1966. }
  1967. ip := net.ParseIP(val)
  1968. return ip != nil && ip.To4() != nil
  1969. }
  1970. func isIP6Addr(fl FieldLevel) bool {
  1971. val := fl.Field().String()
  1972. if idx := strings.LastIndex(val, ":"); idx != -1 {
  1973. if idx != 0 && val[idx-1:idx] == "]" {
  1974. val = val[1 : idx-1]
  1975. }
  1976. }
  1977. ip := net.ParseIP(val)
  1978. return ip != nil && ip.To4() == nil
  1979. }
  1980. func isHostnameRFC952(fl FieldLevel) bool {
  1981. return hostnameRegexRFC952.MatchString(fl.Field().String())
  1982. }
  1983. func isHostnameRFC1123(fl FieldLevel) bool {
  1984. return hostnameRegexRFC1123.MatchString(fl.Field().String())
  1985. }
  1986. func isFQDN(fl FieldLevel) bool {
  1987. val := fl.Field().String()
  1988. if val == "" {
  1989. return false
  1990. }
  1991. return fqdnRegexRFC1123.MatchString(val)
  1992. }
  1993. // isDir is the validation function for validating if the current field's value is a valid existing directory.
  1994. func isDir(fl FieldLevel) bool {
  1995. field := fl.Field()
  1996. if field.Kind() == reflect.String {
  1997. fileInfo, err := os.Stat(field.String())
  1998. if err != nil {
  1999. return false
  2000. }
  2001. return fileInfo.IsDir()
  2002. }
  2003. panic(fmt.Sprintf("Bad field type %T", field.Interface()))
  2004. }
  2005. // isDirPath is the validation function for validating if the current field's value is a valid directory.
  2006. func isDirPath(fl FieldLevel) bool {
  2007. var exists bool
  2008. var err error
  2009. field := fl.Field()
  2010. // If it exists, it obviously is valid.
  2011. // This is done first to avoid code duplication and unnecessary additional logic.
  2012. if exists = isDir(fl); exists {
  2013. return true
  2014. }
  2015. // It does not exist but may still be a valid path.
  2016. switch field.Kind() {
  2017. case reflect.String:
  2018. // Every OS allows for whitespace, but none
  2019. // let you use a dir with no name (to my knowledge).
  2020. // Unless you're dealing with raw inodes, but I digress.
  2021. if strings.TrimSpace(field.String()) == "" {
  2022. return false
  2023. }
  2024. if _, err = os.Stat(field.String()); err != nil {
  2025. switch t := err.(type) {
  2026. case *fs.PathError:
  2027. if t.Err == syscall.EINVAL {
  2028. // It's definitely an invalid character in the path.
  2029. return false
  2030. }
  2031. // It could be a permission error, a does-not-exist error, etc.
  2032. // Out-of-scope for this validation, though.
  2033. // Lastly, we make sure it is a directory.
  2034. if strings.HasSuffix(field.String(), string(os.PathSeparator)) {
  2035. return true
  2036. } else {
  2037. return false
  2038. }
  2039. default:
  2040. // Something went *seriously* wrong.
  2041. /*
  2042. Per https://pkg.go.dev/os#Stat:
  2043. "If there is an error, it will be of type *PathError."
  2044. */
  2045. panic(err)
  2046. }
  2047. }
  2048. // We repeat the check here to make sure it is an explicit directory in case the above os.Stat didn't trigger an error.
  2049. if strings.HasSuffix(field.String(), string(os.PathSeparator)) {
  2050. return true
  2051. } else {
  2052. return false
  2053. }
  2054. }
  2055. panic(fmt.Sprintf("Bad field type %T", field.Interface()))
  2056. }
  2057. // isJSON is the validation function for validating if the current field's value is a valid json string.
  2058. func isJSON(fl FieldLevel) bool {
  2059. field := fl.Field()
  2060. switch field.Kind() {
  2061. case reflect.String:
  2062. val := field.String()
  2063. return json.Valid([]byte(val))
  2064. case reflect.Slice:
  2065. fieldType := field.Type()
  2066. if fieldType.ConvertibleTo(byteSliceType) {
  2067. b := field.Convert(byteSliceType).Interface().([]byte)
  2068. return json.Valid(b)
  2069. }
  2070. }
  2071. panic(fmt.Sprintf("Bad field type %T", field.Interface()))
  2072. }
  2073. // isJWT is the validation function for validating if the current field's value is a valid JWT string.
  2074. func isJWT(fl FieldLevel) bool {
  2075. return jWTRegex.MatchString(fl.Field().String())
  2076. }
  2077. // isHostnamePort validates a <dns>:<port> combination for fields typically used for socket address.
  2078. func isHostnamePort(fl FieldLevel) bool {
  2079. val := fl.Field().String()
  2080. host, port, err := net.SplitHostPort(val)
  2081. if err != nil {
  2082. return false
  2083. }
  2084. // Port must be a iny <= 65535.
  2085. if portNum, err := strconv.ParseInt(
  2086. port, 10, 32,
  2087. ); err != nil || portNum > 65535 || portNum < 1 {
  2088. return false
  2089. }
  2090. // If host is specified, it should match a DNS name
  2091. if host != "" {
  2092. return hostnameRegexRFC1123.MatchString(host)
  2093. }
  2094. return true
  2095. }
  2096. // isLowercase is the validation function for validating if the current field's value is a lowercase string.
  2097. func isLowercase(fl FieldLevel) bool {
  2098. field := fl.Field()
  2099. if field.Kind() == reflect.String {
  2100. if field.String() == "" {
  2101. return false
  2102. }
  2103. return field.String() == strings.ToLower(field.String())
  2104. }
  2105. panic(fmt.Sprintf("Bad field type %T", field.Interface()))
  2106. }
  2107. // isUppercase is the validation function for validating if the current field's value is an uppercase string.
  2108. func isUppercase(fl FieldLevel) bool {
  2109. field := fl.Field()
  2110. if field.Kind() == reflect.String {
  2111. if field.String() == "" {
  2112. return false
  2113. }
  2114. return field.String() == strings.ToUpper(field.String())
  2115. }
  2116. panic(fmt.Sprintf("Bad field type %T", field.Interface()))
  2117. }
  2118. // isDatetime is the validation function for validating if the current field's value is a valid datetime string.
  2119. func isDatetime(fl FieldLevel) bool {
  2120. field := fl.Field()
  2121. param := fl.Param()
  2122. if field.Kind() == reflect.String {
  2123. _, err := time.Parse(param, field.String())
  2124. return err == nil
  2125. }
  2126. panic(fmt.Sprintf("Bad field type %T", field.Interface()))
  2127. }
  2128. // isTimeZone is the validation function for validating if the current field's value is a valid time zone string.
  2129. func isTimeZone(fl FieldLevel) bool {
  2130. field := fl.Field()
  2131. if field.Kind() == reflect.String {
  2132. // empty value is converted to UTC by time.LoadLocation but disallow it as it is not a valid time zone name
  2133. if field.String() == "" {
  2134. return false
  2135. }
  2136. // Local value is converted to the current system time zone by time.LoadLocation but disallow it as it is not a valid time zone name
  2137. if strings.ToLower(field.String()) == "local" {
  2138. return false
  2139. }
  2140. _, err := time.LoadLocation(field.String())
  2141. return err == nil
  2142. }
  2143. panic(fmt.Sprintf("Bad field type %T", field.Interface()))
  2144. }
  2145. // isIso3166Alpha2 is the validation function for validating if the current field's value is a valid iso3166-1 alpha-2 country code.
  2146. func isIso3166Alpha2(fl FieldLevel) bool {
  2147. val := fl.Field().String()
  2148. return iso3166_1_alpha2[val]
  2149. }
  2150. // isIso3166Alpha2EU is the validation function for validating if the current field's value is a valid iso3166-1 alpha-2 European Union country code.
  2151. func isIso3166Alpha2EU(fl FieldLevel) bool {
  2152. val := fl.Field().String()
  2153. return iso3166_1_alpha2_eu[val]
  2154. }
  2155. // isIso3166Alpha3 is the validation function for validating if the current field's value is a valid iso3166-1 alpha-3 country code.
  2156. func isIso3166Alpha3(fl FieldLevel) bool {
  2157. val := fl.Field().String()
  2158. return iso3166_1_alpha3[val]
  2159. }
  2160. // isIso3166Alpha3EU is the validation function for validating if the current field's value is a valid iso3166-1 alpha-3 European Union country code.
  2161. func isIso3166Alpha3EU(fl FieldLevel) bool {
  2162. val := fl.Field().String()
  2163. return iso3166_1_alpha3_eu[val]
  2164. }
  2165. // isIso3166AlphaNumeric is the validation function for validating if the current field's value is a valid iso3166-1 alpha-numeric country code.
  2166. func isIso3166AlphaNumeric(fl FieldLevel) bool {
  2167. field := fl.Field()
  2168. var code int
  2169. switch field.Kind() {
  2170. case reflect.String:
  2171. i, err := strconv.Atoi(field.String())
  2172. if err != nil {
  2173. return false
  2174. }
  2175. code = i % 1000
  2176. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  2177. code = int(field.Int() % 1000)
  2178. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  2179. code = int(field.Uint() % 1000)
  2180. default:
  2181. panic(fmt.Sprintf("Bad field type %T", field.Interface()))
  2182. }
  2183. return iso3166_1_alpha_numeric[code]
  2184. }
  2185. // isIso3166AlphaNumericEU is the validation function for validating if the current field's value is a valid iso3166-1 alpha-numeric European Union country code.
  2186. func isIso3166AlphaNumericEU(fl FieldLevel) bool {
  2187. field := fl.Field()
  2188. var code int
  2189. switch field.Kind() {
  2190. case reflect.String:
  2191. i, err := strconv.Atoi(field.String())
  2192. if err != nil {
  2193. return false
  2194. }
  2195. code = i % 1000
  2196. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  2197. code = int(field.Int() % 1000)
  2198. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  2199. code = int(field.Uint() % 1000)
  2200. default:
  2201. panic(fmt.Sprintf("Bad field type %T", field.Interface()))
  2202. }
  2203. return iso3166_1_alpha_numeric_eu[code]
  2204. }
  2205. // isIso31662 is the validation function for validating if the current field's value is a valid iso3166-2 code.
  2206. func isIso31662(fl FieldLevel) bool {
  2207. val := fl.Field().String()
  2208. return iso3166_2[val]
  2209. }
  2210. // isIso4217 is the validation function for validating if the current field's value is a valid iso4217 currency code.
  2211. func isIso4217(fl FieldLevel) bool {
  2212. val := fl.Field().String()
  2213. return iso4217[val]
  2214. }
  2215. // isIso4217Numeric is the validation function for validating if the current field's value is a valid iso4217 numeric currency code.
  2216. func isIso4217Numeric(fl FieldLevel) bool {
  2217. field := fl.Field()
  2218. var code int
  2219. switch field.Kind() {
  2220. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  2221. code = int(field.Int())
  2222. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  2223. code = int(field.Uint())
  2224. default:
  2225. panic(fmt.Sprintf("Bad field type %T", field.Interface()))
  2226. }
  2227. return iso4217_numeric[code]
  2228. }
  2229. // isBCP47LanguageTag is the validation function for validating if the current field's value is a valid BCP 47 language tag, as parsed by language.Parse
  2230. func isBCP47LanguageTag(fl FieldLevel) bool {
  2231. field := fl.Field()
  2232. if field.Kind() == reflect.String {
  2233. _, err := language.Parse(field.String())
  2234. return err == nil
  2235. }
  2236. panic(fmt.Sprintf("Bad field type %T", field.Interface()))
  2237. }
  2238. // isIsoBicFormat is the validation function for validating if the current field's value is a valid Business Identifier Code (SWIFT code), defined in ISO 9362
  2239. func isIsoBicFormat(fl FieldLevel) bool {
  2240. bicString := fl.Field().String()
  2241. return bicRegex.MatchString(bicString)
  2242. }
  2243. // isSemverFormat is the validation function for validating if the current field's value is a valid semver version, defined in Semantic Versioning 2.0.0
  2244. func isSemverFormat(fl FieldLevel) bool {
  2245. semverString := fl.Field().String()
  2246. return semverRegex.MatchString(semverString)
  2247. }
  2248. // isCveFormat is the validation function for validating if the current field's value is a valid cve id, defined in CVE mitre org
  2249. func isCveFormat(fl FieldLevel) bool {
  2250. cveString := fl.Field().String()
  2251. return cveRegex.MatchString(cveString)
  2252. }
  2253. // isDnsRFC1035LabelFormat is the validation function
  2254. // for validating if the current field's value is
  2255. // a valid dns RFC 1035 label, defined in RFC 1035.
  2256. func isDnsRFC1035LabelFormat(fl FieldLevel) bool {
  2257. val := fl.Field().String()
  2258. return dnsRegexRFC1035Label.MatchString(val)
  2259. }
  2260. // digitsHaveLuhnChecksum returns true if and only if the last element of the given digits slice is the Luhn checksum of the previous elements
  2261. func digitsHaveLuhnChecksum(digits []string) bool {
  2262. size := len(digits)
  2263. sum := 0
  2264. for i, digit := range digits {
  2265. value, err := strconv.Atoi(digit)
  2266. if err != nil {
  2267. return false
  2268. }
  2269. if size%2 == 0 && i%2 == 0 || size%2 == 1 && i%2 == 1 {
  2270. v := value * 2
  2271. if v >= 10 {
  2272. sum += 1 + (v % 10)
  2273. } else {
  2274. sum += v
  2275. }
  2276. } else {
  2277. sum += value
  2278. }
  2279. }
  2280. return (sum % 10) == 0
  2281. }
  2282. // isMongoDB is the validation function for validating if the current field's value is valid mongoDB objectID
  2283. func isMongoDB(fl FieldLevel) bool {
  2284. val := fl.Field().String()
  2285. return mongodbRegex.MatchString(val)
  2286. }
  2287. // isSpiceDB is the validation function for validating if the current field's value is valid for use with Authzed SpiceDB in the indicated way
  2288. func isSpiceDB(fl FieldLevel) bool {
  2289. val := fl.Field().String()
  2290. param := fl.Param()
  2291. switch param {
  2292. case "permission":
  2293. return spicedbPermissionRegex.MatchString(val)
  2294. case "type":
  2295. return spicedbTypeRegex.MatchString(val)
  2296. case "id", "":
  2297. return spicedbIDRegex.MatchString(val)
  2298. }
  2299. panic("Unrecognized parameter: " + param)
  2300. }
  2301. // isCreditCard is the validation function for validating if the current field's value is a valid credit card number
  2302. func isCreditCard(fl FieldLevel) bool {
  2303. val := fl.Field().String()
  2304. var creditCard bytes.Buffer
  2305. segments := strings.Split(val, " ")
  2306. for _, segment := range segments {
  2307. if len(segment) < 3 {
  2308. return false
  2309. }
  2310. creditCard.WriteString(segment)
  2311. }
  2312. ccDigits := strings.Split(creditCard.String(), "")
  2313. size := len(ccDigits)
  2314. if size < 12 || size > 19 {
  2315. return false
  2316. }
  2317. return digitsHaveLuhnChecksum(ccDigits)
  2318. }
  2319. // hasLuhnChecksum is the validation for validating if the current field's value has a valid Luhn checksum
  2320. func hasLuhnChecksum(fl FieldLevel) bool {
  2321. field := fl.Field()
  2322. var str string // convert to a string which will then be split into single digits; easier and more readable than shifting/extracting single digits from a number
  2323. switch field.Kind() {
  2324. case reflect.String:
  2325. str = field.String()
  2326. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  2327. str = strconv.FormatInt(field.Int(), 10)
  2328. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  2329. str = strconv.FormatUint(field.Uint(), 10)
  2330. default:
  2331. panic(fmt.Sprintf("Bad field type %T", field.Interface()))
  2332. }
  2333. size := len(str)
  2334. if size < 2 { // there has to be at least one digit that carries a meaning + the checksum
  2335. return false
  2336. }
  2337. digits := strings.Split(str, "")
  2338. return digitsHaveLuhnChecksum(digits)
  2339. }
  2340. // isCron is the validation function for validating if the current field's value is a valid cron expression
  2341. func isCron(fl FieldLevel) bool {
  2342. cronString := fl.Field().String()
  2343. return cronRegex.MatchString(cronString)
  2344. }