baked_in.go 73 KB

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