doc.go 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504
  1. /*
  2. Package validator implements value validations for structs and individual fields
  3. based on tags.
  4. It can also handle Cross-Field and Cross-Struct validation for nested structs
  5. and has the ability to dive into arrays and maps of any type.
  6. see more examples https://github.com/go-playground/validator/tree/master/_examples
  7. # Singleton
  8. Validator is designed to be thread-safe and used as a singleton instance.
  9. It caches information about your struct and validations,
  10. in essence only parsing your validation tags once per struct type.
  11. Using multiple instances neglects the benefit of caching.
  12. The not thread-safe functions are explicitly marked as such in the documentation.
  13. # Validation Functions Return Type error
  14. Doing things this way is actually the way the standard library does, see the
  15. file.Open method here:
  16. https://golang.org/pkg/os/#Open.
  17. The authors return type "error" to avoid the issue discussed in the following,
  18. where err is always != nil:
  19. http://stackoverflow.com/a/29138676/3158232
  20. https://github.com/go-playground/validator/issues/134
  21. Validator only InvalidValidationError for bad validation input, nil or
  22. ValidationErrors as type error; so, in your code all you need to do is check
  23. if the error returned is not nil, and if it's not check if error is
  24. InvalidValidationError ( if necessary, most of the time it isn't ) type cast
  25. it to type ValidationErrors like so err.(validator.ValidationErrors).
  26. # Custom Validation Functions
  27. Custom Validation functions can be added. Example:
  28. // Structure
  29. func customFunc(fl validator.FieldLevel) bool {
  30. if fl.Field().String() == "invalid" {
  31. return false
  32. }
  33. return true
  34. }
  35. validate.RegisterValidation("custom tag name", customFunc)
  36. // NOTES: using the same tag name as an existing function
  37. // will overwrite the existing one
  38. # Cross-Field Validation
  39. Cross-Field Validation can be done via the following tags:
  40. - eqfield
  41. - nefield
  42. - gtfield
  43. - gtefield
  44. - ltfield
  45. - ltefield
  46. - eqcsfield
  47. - necsfield
  48. - gtcsfield
  49. - gtecsfield
  50. - ltcsfield
  51. - ltecsfield
  52. If, however, some custom cross-field validation is required, it can be done
  53. using a custom validation.
  54. Why not just have cross-fields validation tags (i.e. only eqcsfield and not
  55. eqfield)?
  56. The reason is efficiency. If you want to check a field within the same struct
  57. "eqfield" only has to find the field on the same struct (1 level). But, if we
  58. used "eqcsfield" it could be multiple levels down. Example:
  59. type Inner struct {
  60. StartDate time.Time
  61. }
  62. type Outer struct {
  63. InnerStructField *Inner
  64. CreatedAt time.Time `validate:"ltecsfield=InnerStructField.StartDate"`
  65. }
  66. now := time.Now()
  67. inner := &Inner{
  68. StartDate: now,
  69. }
  70. outer := &Outer{
  71. InnerStructField: inner,
  72. CreatedAt: now,
  73. }
  74. errs := validate.Struct(outer)
  75. // NOTE: when calling validate.Struct(val) topStruct will be the top level struct passed
  76. // into the function
  77. // when calling validate.VarWithValue(val, field, tag) val will be
  78. // whatever you pass, struct, field...
  79. // when calling validate.Field(field, tag) val will be nil
  80. # Multiple Validators
  81. Multiple validators on a field will process in the order defined. Example:
  82. type Test struct {
  83. Field `validate:"max=10,min=1"`
  84. }
  85. // max will be checked then min
  86. Bad Validator definitions are not handled by the library. Example:
  87. type Test struct {
  88. Field `validate:"min=10,max=0"`
  89. }
  90. // this definition of min max will never succeed
  91. # Using Validator Tags
  92. Baked In Cross-Field validation only compares fields on the same struct.
  93. If Cross-Field + Cross-Struct validation is needed you should implement your
  94. own custom validator.
  95. Comma (",") is the default separator of validation tags. If you wish to
  96. have a comma included within the parameter (i.e. excludesall=,) you will need to
  97. use the UTF-8 hex representation 0x2C, which is replaced in the code as a comma,
  98. so the above will become excludesall=0x2C.
  99. type Test struct {
  100. Field `validate:"excludesall=,"` // BAD! Do not include a comma.
  101. Field `validate:"excludesall=0x2C"` // GOOD! Use the UTF-8 hex representation.
  102. }
  103. Pipe ("|") is the 'or' validation tags deparator. If you wish to
  104. have a pipe included within the parameter i.e. excludesall=| you will need to
  105. use the UTF-8 hex representation 0x7C, which is replaced in the code as a pipe,
  106. so the above will become excludesall=0x7C
  107. type Test struct {
  108. Field `validate:"excludesall=|"` // BAD! Do not include a pipe!
  109. Field `validate:"excludesall=0x7C"` // GOOD! Use the UTF-8 hex representation.
  110. }
  111. # Baked In Validators and Tags
  112. Here is a list of the current built in validators:
  113. # Skip Field
  114. Tells the validation to skip this struct field; this is particularly
  115. handy in ignoring embedded structs from being validated. (Usage: -)
  116. Usage: -
  117. # Or Operator
  118. This is the 'or' operator allowing multiple validators to be used and
  119. accepted. (Usage: rgb|rgba) <-- this would allow either rgb or rgba
  120. colors to be accepted. This can also be combined with 'and' for example
  121. ( Usage: omitempty,rgb|rgba)
  122. Usage: |
  123. # StructOnly
  124. When a field that is a nested struct is encountered, and contains this flag
  125. any validation on the nested struct will be run, but none of the nested
  126. struct fields will be validated. This is useful if inside of your program
  127. you know the struct will be valid, but need to verify it has been assigned.
  128. NOTE: only "required" and "omitempty" can be used on a struct itself.
  129. Usage: structonly
  130. # NoStructLevel
  131. Same as structonly tag except that any struct level validations will not run.
  132. Usage: nostructlevel
  133. # Omit Empty
  134. Allows conditional validation, for example if a field is not set with
  135. a value (Determined by the "required" validator) then other validation
  136. such as min or max won't run, but if a value is set validation will run.
  137. Usage: omitempty
  138. # Omit Nil
  139. Allows to skip the validation if the value is nil (same as omitempty, but
  140. only for the nil-values).
  141. Usage: omitnil
  142. # Dive
  143. This tells the validator to dive into a slice, array or map and validate that
  144. level of the slice, array or map with the validation tags that follow.
  145. Multidimensional nesting is also supported, each level you wish to dive will
  146. require another dive tag. dive has some sub-tags, 'keys' & 'endkeys', please see
  147. the Keys & EndKeys section just below.
  148. Usage: dive
  149. Example #1
  150. [][]string with validation tag "gt=0,dive,len=1,dive,required"
  151. // gt=0 will be applied to []
  152. // len=1 will be applied to []string
  153. // required will be applied to string
  154. Example #2
  155. [][]string with validation tag "gt=0,dive,dive,required"
  156. // gt=0 will be applied to []
  157. // []string will be spared validation
  158. // required will be applied to string
  159. Keys & EndKeys
  160. These are to be used together directly after the dive tag and tells the validator
  161. that anything between 'keys' and 'endkeys' applies to the keys of a map and not the
  162. values; think of it like the 'dive' tag, but for map keys instead of values.
  163. Multidimensional nesting is also supported, each level you wish to validate will
  164. require another 'keys' and 'endkeys' tag. These tags are only valid for maps.
  165. Usage: dive,keys,othertagvalidation(s),endkeys,valuevalidationtags
  166. Example #1
  167. map[string]string with validation tag "gt=0,dive,keys,eq=1|eq=2,endkeys,required"
  168. // gt=0 will be applied to the map itself
  169. // eq=1|eq=2 will be applied to the map keys
  170. // required will be applied to map values
  171. Example #2
  172. map[[2]string]string with validation tag "gt=0,dive,keys,dive,eq=1|eq=2,endkeys,required"
  173. // gt=0 will be applied to the map itself
  174. // eq=1|eq=2 will be applied to each array element in the map keys
  175. // required will be applied to map values
  176. # Required
  177. This validates that the value is not the data types default zero value.
  178. For numbers ensures value is not zero. For strings ensures value is
  179. not "". For booleans ensures value is not false. For slices, maps, pointers, interfaces, channels and functions
  180. ensures the value is not nil. For structs ensures value is not the zero value when using WithRequiredStructEnabled.
  181. Usage: required
  182. # Required If
  183. The field under validation must be present and not empty only if all
  184. the other specified fields are equal to the value following the specified
  185. field. For strings ensures value is not "". For slices, maps, pointers,
  186. interfaces, channels and functions ensures the value is not nil. For structs ensures value is not the zero value.
  187. Usage: required_if
  188. Examples:
  189. // require the field if the Field1 is equal to the parameter given:
  190. Usage: required_if=Field1 foobar
  191. // require the field if the Field1 and Field2 is equal to the value respectively:
  192. Usage: required_if=Field1 foo Field2 bar
  193. # Required Unless
  194. The field under validation must be present and not empty unless all
  195. the other specified fields are equal to the value following the specified
  196. field. For strings ensures value is not "". For slices, maps, pointers,
  197. interfaces, channels and functions ensures the value is not nil. For structs ensures value is not the zero value.
  198. Usage: required_unless
  199. Examples:
  200. // require the field unless the Field1 is equal to the parameter given:
  201. Usage: required_unless=Field1 foobar
  202. // require the field unless the Field1 and Field2 is equal to the value respectively:
  203. Usage: required_unless=Field1 foo Field2 bar
  204. # Required With
  205. The field under validation must be present and not empty only if any
  206. of the other specified fields are present. For strings ensures value is
  207. not "". For slices, maps, pointers, interfaces, channels and functions
  208. ensures the value is not nil. For structs ensures value is not the zero value.
  209. Usage: required_with
  210. Examples:
  211. // require the field if the Field1 is present:
  212. Usage: required_with=Field1
  213. // require the field if the Field1 or Field2 is present:
  214. Usage: required_with=Field1 Field2
  215. # Required With All
  216. The field under validation must be present and not empty only if all
  217. of the other specified fields are present. For strings ensures value is
  218. not "". For slices, maps, pointers, interfaces, channels and functions
  219. ensures the value is not nil. For structs ensures value is not the zero value.
  220. Usage: required_with_all
  221. Example:
  222. // require the field if the Field1 and Field2 is present:
  223. Usage: required_with_all=Field1 Field2
  224. # Required Without
  225. The field under validation must be present and not empty only when any
  226. of the other specified fields are not present. For strings ensures value is
  227. not "". For slices, maps, pointers, interfaces, channels and functions
  228. ensures the value is not nil. For structs ensures value is not the zero value.
  229. Usage: required_without
  230. Examples:
  231. // require the field if the Field1 is not present:
  232. Usage: required_without=Field1
  233. // require the field if the Field1 or Field2 is not present:
  234. Usage: required_without=Field1 Field2
  235. # Required Without All
  236. The field under validation must be present and not empty only when all
  237. of the other specified fields are not present. For strings ensures value is
  238. not "". For slices, maps, pointers, interfaces, channels and functions
  239. ensures the value is not nil. For structs ensures value is not the zero value.
  240. Usage: required_without_all
  241. Example:
  242. // require the field if the Field1 and Field2 is not present:
  243. Usage: required_without_all=Field1 Field2
  244. # Excluded If
  245. The field under validation must not be present or not empty only if all
  246. the other specified fields are equal to the value following the specified
  247. field. For strings ensures value is not "". For slices, maps, pointers,
  248. interfaces, channels and functions ensures the value is not nil. For structs ensures value is not the zero value.
  249. Usage: excluded_if
  250. Examples:
  251. // exclude the field if the Field1 is equal to the parameter given:
  252. Usage: excluded_if=Field1 foobar
  253. // exclude the field if the Field1 and Field2 is equal to the value respectively:
  254. Usage: excluded_if=Field1 foo Field2 bar
  255. # Excluded Unless
  256. The field under validation must not be present or empty unless all
  257. the other specified fields are equal to the value following the specified
  258. field. For strings ensures value is not "". For slices, maps, pointers,
  259. interfaces, channels and functions ensures the value is not nil. For structs ensures value is not the zero value.
  260. Usage: excluded_unless
  261. Examples:
  262. // exclude the field unless the Field1 is equal to the parameter given:
  263. Usage: excluded_unless=Field1 foobar
  264. // exclude the field unless the Field1 and Field2 is equal to the value respectively:
  265. Usage: excluded_unless=Field1 foo Field2 bar
  266. # Is Default
  267. This validates that the value is the default value and is almost the
  268. opposite of required.
  269. Usage: isdefault
  270. # Length
  271. For numbers, length will ensure that the value is
  272. equal to the parameter given. For strings, it checks that
  273. the string length is exactly that number of characters. For slices,
  274. arrays, and maps, validates the number of items.
  275. Example #1
  276. Usage: len=10
  277. Example #2 (time.Duration)
  278. For time.Duration, len will ensure that the value is equal to the duration given
  279. in the parameter.
  280. Usage: len=1h30m
  281. # Maximum
  282. For numbers, max will ensure that the value is
  283. less than or equal to the parameter given. For strings, it checks
  284. that the string length is at most that number of characters. For
  285. slices, arrays, and maps, validates the number of items.
  286. Example #1
  287. Usage: max=10
  288. Example #2 (time.Duration)
  289. For time.Duration, max will ensure that the value is less than or equal to the
  290. duration given in the parameter.
  291. Usage: max=1h30m
  292. # Minimum
  293. For numbers, min will ensure that the value is
  294. greater or equal to the parameter given. For strings, it checks that
  295. the string length is at least that number of characters. For slices,
  296. arrays, and maps, validates the number of items.
  297. Example #1
  298. Usage: min=10
  299. Example #2 (time.Duration)
  300. For time.Duration, min will ensure that the value is greater than or equal to
  301. the duration given in the parameter.
  302. Usage: min=1h30m
  303. # Equals
  304. For strings & numbers, eq will ensure that the value is
  305. equal to the parameter given. For slices, arrays, and maps,
  306. validates the number of items.
  307. Example #1
  308. Usage: eq=10
  309. Example #2 (time.Duration)
  310. For time.Duration, eq will ensure that the value is equal to the duration given
  311. in the parameter.
  312. Usage: eq=1h30m
  313. # Not Equal
  314. For strings & numbers, ne will ensure that the value is not
  315. equal to the parameter given. For slices, arrays, and maps,
  316. validates the number of items.
  317. Example #1
  318. Usage: ne=10
  319. Example #2 (time.Duration)
  320. For time.Duration, ne will ensure that the value is not equal to the duration
  321. given in the parameter.
  322. Usage: ne=1h30m
  323. # One Of
  324. For strings, ints, and uints, oneof will ensure that the value
  325. is one of the values in the parameter. The parameter should be
  326. a list of values separated by whitespace. Values may be
  327. strings or numbers. To match strings with spaces in them, include
  328. the target string between single quotes. Kind of like an 'enum'.
  329. Usage: oneof=red green
  330. oneof='red green' 'blue yellow'
  331. oneof=5 7 9
  332. # One Of Case Insensitive
  333. Works the same as oneof but is case insensitive and therefore only accepts strings.
  334. Usage: oneofci=red green
  335. oneofci='red green' 'blue yellow'
  336. # Greater Than
  337. For numbers, this will ensure that the value is greater than the
  338. parameter given. For strings, it checks that the string length
  339. is greater than that number of characters. For slices, arrays
  340. and maps it validates the number of items.
  341. Example #1
  342. Usage: gt=10
  343. Example #2 (time.Time)
  344. For time.Time ensures the time value is greater than time.Now.UTC().
  345. Usage: gt
  346. Example #3 (time.Duration)
  347. For time.Duration, gt will ensure that the value is greater than the duration
  348. given in the parameter.
  349. Usage: gt=1h30m
  350. # Greater Than or Equal
  351. Same as 'min' above. Kept both to make terminology with 'len' easier.
  352. Example #1
  353. Usage: gte=10
  354. Example #2 (time.Time)
  355. For time.Time ensures the time value is greater than or equal to time.Now.UTC().
  356. Usage: gte
  357. Example #3 (time.Duration)
  358. For time.Duration, gte will ensure that the value is greater than or equal to
  359. the duration given in the parameter.
  360. Usage: gte=1h30m
  361. # Less Than
  362. For numbers, this will ensure that the value is less than the parameter given.
  363. For strings, it checks that the string length is less than that number of
  364. characters. For slices, arrays, and maps it validates the number of items.
  365. Example #1
  366. Usage: lt=10
  367. Example #2 (time.Time)
  368. For time.Time ensures the time value is less than time.Now.UTC().
  369. Usage: lt
  370. Example #3 (time.Duration)
  371. For time.Duration, lt will ensure that the value is less than the duration given
  372. in the parameter.
  373. Usage: lt=1h30m
  374. # Less Than or Equal
  375. Same as 'max' above. Kept both to make terminology with 'len' easier.
  376. Example #1
  377. Usage: lte=10
  378. Example #2 (time.Time)
  379. For time.Time ensures the time value is less than or equal to time.Now.UTC().
  380. Usage: lte
  381. Example #3 (time.Duration)
  382. For time.Duration, lte will ensure that the value is less than or equal to the
  383. duration given in the parameter.
  384. Usage: lte=1h30m
  385. # Field Equals Another Field
  386. This will validate the field value against another fields value either within
  387. a struct or passed in field.
  388. Example #1:
  389. // Validation on Password field using:
  390. Usage: eqfield=ConfirmPassword
  391. Example #2:
  392. // Validating by field:
  393. validate.VarWithValue(password, confirmpassword, "eqfield")
  394. Field Equals Another Field (relative)
  395. This does the same as eqfield except that it validates the field provided relative
  396. to the top level struct.
  397. Usage: eqcsfield=InnerStructField.Field)
  398. # Field Does Not Equal Another Field
  399. This will validate the field value against another fields value either within
  400. a struct or passed in field.
  401. Examples:
  402. // Confirm two colors are not the same:
  403. //
  404. // Validation on Color field:
  405. Usage: nefield=Color2
  406. // Validating by field:
  407. validate.VarWithValue(color1, color2, "nefield")
  408. Field Does Not Equal Another Field (relative)
  409. This does the same as nefield except that it validates the field provided
  410. relative to the top level struct.
  411. Usage: necsfield=InnerStructField.Field
  412. # Field Greater Than Another Field
  413. Only valid for Numbers, time.Duration and time.Time types, this will validate
  414. the field value against another fields value either within a struct or passed in
  415. field. usage examples are for validation of a Start and End date:
  416. Example #1:
  417. // Validation on End field using:
  418. validate.Struct Usage(gtfield=Start)
  419. Example #2:
  420. // Validating by field:
  421. validate.VarWithValue(start, end, "gtfield")
  422. # Field Greater Than Another Relative Field
  423. This does the same as gtfield except that it validates the field provided
  424. relative to the top level struct.
  425. Usage: gtcsfield=InnerStructField.Field
  426. # Field Greater Than or Equal To Another Field
  427. Only valid for Numbers, time.Duration and time.Time types, this will validate
  428. the field value against another fields value either within a struct or passed in
  429. field. usage examples are for validation of a Start and End date:
  430. Example #1:
  431. // Validation on End field using:
  432. validate.Struct Usage(gtefield=Start)
  433. Example #2:
  434. // Validating by field:
  435. validate.VarWithValue(start, end, "gtefield")
  436. # Field Greater Than or Equal To Another Relative Field
  437. This does the same as gtefield except that it validates the field provided relative
  438. to the top level struct.
  439. Usage: gtecsfield=InnerStructField.Field
  440. # Less Than Another Field
  441. Only valid for Numbers, time.Duration and time.Time types, this will validate
  442. the field value against another fields value either within a struct or passed in
  443. field. usage examples are for validation of a Start and End date:
  444. Example #1:
  445. // Validation on End field using:
  446. validate.Struct Usage(ltfield=Start)
  447. Example #2:
  448. // Validating by field:
  449. validate.VarWithValue(start, end, "ltfield")
  450. # Less Than Another Relative Field
  451. This does the same as ltfield except that it validates the field provided relative
  452. to the top level struct.
  453. Usage: ltcsfield=InnerStructField.Field
  454. # Less Than or Equal To Another Field
  455. Only valid for Numbers, time.Duration and time.Time types, this will validate
  456. the field value against another fields value either within a struct or passed in
  457. field. usage examples are for validation of a Start and End date:
  458. Example #1:
  459. // Validation on End field using:
  460. validate.Struct Usage(ltefield=Start)
  461. Example #2:
  462. // Validating by field:
  463. validate.VarWithValue(start, end, "ltefield")
  464. # Less Than or Equal To Another Relative Field
  465. This does the same as ltefield except that it validates the field provided relative
  466. to the top level struct.
  467. Usage: ltecsfield=InnerStructField.Field
  468. # Field Contains Another Field
  469. This does the same as contains except for struct fields. It should only be used
  470. with string types. See the behavior of reflect.Value.String() for behavior on
  471. other types.
  472. Usage: containsfield=InnerStructField.Field
  473. # Field Excludes Another Field
  474. This does the same as excludes except for struct fields. It should only be used
  475. with string types. See the behavior of reflect.Value.String() for behavior on
  476. other types.
  477. Usage: excludesfield=InnerStructField.Field
  478. # Unique
  479. For arrays & slices, unique will ensure that there are no duplicates.
  480. For maps, unique will ensure that there are no duplicate values.
  481. For slices of struct, unique will ensure that there are no duplicate values
  482. in a field of the struct specified via a parameter.
  483. // For arrays, slices, and maps:
  484. Usage: unique
  485. // For slices of struct:
  486. Usage: unique=field
  487. # Alpha Only
  488. This validates that a string value contains ASCII alpha characters only
  489. Usage: alpha
  490. # Alphanumeric
  491. This validates that a string value contains ASCII alphanumeric characters only
  492. Usage: alphanum
  493. # Alpha Unicode
  494. This validates that a string value contains unicode alpha characters only
  495. Usage: alphaunicode
  496. # Alphanumeric Unicode
  497. This validates that a string value contains unicode alphanumeric characters only
  498. Usage: alphanumunicode
  499. # Boolean
  500. This validates that a string value can successfully be parsed into a boolean with strconv.ParseBool
  501. Usage: boolean
  502. # Number
  503. This validates that a string value contains number values only.
  504. For integers or float it returns true.
  505. Usage: number
  506. # Numeric
  507. This validates that a string value contains a basic numeric value.
  508. basic excludes exponents etc...
  509. for integers or float it returns true.
  510. Usage: numeric
  511. # Hexadecimal String
  512. This validates that a string value contains a valid hexadecimal.
  513. Usage: hexadecimal
  514. # Hexcolor String
  515. This validates that a string value contains a valid hex color including
  516. hashtag (#)
  517. Usage: hexcolor
  518. # Lowercase String
  519. This validates that a string value contains only lowercase characters. An empty string is not a valid lowercase string.
  520. Usage: lowercase
  521. # Uppercase String
  522. This validates that a string value contains only uppercase characters. An empty string is not a valid uppercase string.
  523. Usage: uppercase
  524. # RGB String
  525. This validates that a string value contains a valid rgb color
  526. Usage: rgb
  527. # RGBA String
  528. This validates that a string value contains a valid rgba color
  529. Usage: rgba
  530. # HSL String
  531. This validates that a string value contains a valid hsl color
  532. Usage: hsl
  533. # HSLA String
  534. This validates that a string value contains a valid hsla color
  535. Usage: hsla
  536. # E.164 Phone Number String
  537. This validates that a string value contains a valid E.164 Phone number
  538. https://en.wikipedia.org/wiki/E.164 (ex. +1123456789)
  539. Usage: e164
  540. # E-mail String
  541. This validates that a string value contains a valid email
  542. This may not conform to all possibilities of any rfc standard, but neither
  543. does any email provider accept all possibilities.
  544. Usage: email
  545. # JSON String
  546. This validates that a string value is valid JSON
  547. Usage: json
  548. # JWT String
  549. This validates that a string value is a valid JWT
  550. Usage: jwt
  551. # File
  552. This validates that a string value contains a valid file path and that
  553. the file exists on the machine.
  554. This is done using os.Stat, which is a platform independent function.
  555. Usage: file
  556. # Image path
  557. This validates that a string value contains a valid file path and that
  558. the file exists on the machine and is an image.
  559. This is done using os.Stat and github.com/gabriel-vasile/mimetype
  560. Usage: image
  561. # File Path
  562. This validates that a string value contains a valid file path but does not
  563. validate the existence of that file.
  564. This is done using os.Stat, which is a platform independent function.
  565. Usage: filepath
  566. # URL String
  567. This validates that a string value contains a valid url
  568. This will accept any url the golang request uri accepts but must contain
  569. a schema for example http:// or rtmp://
  570. Usage: url
  571. # URI String
  572. This validates that a string value contains a valid uri
  573. This will accept any uri the golang request uri accepts
  574. Usage: uri
  575. # Urn RFC 2141 String
  576. This validates that a string value contains a valid URN
  577. according to the RFC 2141 spec.
  578. Usage: urn_rfc2141
  579. # Base32 String
  580. This validates that a string value contains a valid bas324 value.
  581. Although an empty string is valid base32 this will report an empty string
  582. as an error, if you wish to accept an empty string as valid you can use
  583. this with the omitempty tag.
  584. Usage: base32
  585. # Base64 String
  586. This validates that a string value contains a valid base64 value.
  587. Although an empty string is valid base64 this will report an empty string
  588. as an error, if you wish to accept an empty string as valid you can use
  589. this with the omitempty tag.
  590. Usage: base64
  591. # Base64URL String
  592. This validates that a string value contains a valid base64 URL safe value
  593. according the RFC4648 spec.
  594. Although an empty string is a valid base64 URL safe value, this will report
  595. an empty string as an error, if you wish to accept an empty string as valid
  596. you can use this with the omitempty tag.
  597. Usage: base64url
  598. # Base64RawURL String
  599. This validates that a string value contains a valid base64 URL safe value,
  600. but without = padding, according the RFC4648 spec, section 3.2.
  601. Although an empty string is a valid base64 URL safe value, this will report
  602. an empty string as an error, if you wish to accept an empty string as valid
  603. you can use this with the omitempty tag.
  604. Usage: base64rawurl
  605. # Bitcoin Address
  606. This validates that a string value contains a valid bitcoin address.
  607. The format of the string is checked to ensure it matches one of the three formats
  608. P2PKH, P2SH and performs checksum validation.
  609. Usage: btc_addr
  610. Bitcoin Bech32 Address (segwit)
  611. This validates that a string value contains a valid bitcoin Bech32 address as defined
  612. by bip-0173 (https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki)
  613. Special thanks to Pieter Wuille for providing reference implementations.
  614. Usage: btc_addr_bech32
  615. # Ethereum Address
  616. This validates that a string value contains a valid ethereum address.
  617. The format of the string is checked to ensure it matches the standard Ethereum address format.
  618. Usage: eth_addr
  619. # Contains
  620. This validates that a string value contains the substring value.
  621. Usage: contains=@
  622. # Contains Any
  623. This validates that a string value contains any Unicode code points
  624. in the substring value.
  625. Usage: containsany=!@#?
  626. # Contains Rune
  627. This validates that a string value contains the supplied rune value.
  628. Usage: containsrune=@
  629. # Excludes
  630. This validates that a string value does not contain the substring value.
  631. Usage: excludes=@
  632. # Excludes All
  633. This validates that a string value does not contain any Unicode code
  634. points in the substring value.
  635. Usage: excludesall=!@#?
  636. # Excludes Rune
  637. This validates that a string value does not contain the supplied rune value.
  638. Usage: excludesrune=@
  639. # Starts With
  640. This validates that a string value starts with the supplied string value
  641. Usage: startswith=hello
  642. # Ends With
  643. This validates that a string value ends with the supplied string value
  644. Usage: endswith=goodbye
  645. # Does Not Start With
  646. This validates that a string value does not start with the supplied string value
  647. Usage: startsnotwith=hello
  648. # Does Not End With
  649. This validates that a string value does not end with the supplied string value
  650. Usage: endsnotwith=goodbye
  651. # International Standard Book Number
  652. This validates that a string value contains a valid isbn10 or isbn13 value.
  653. Usage: isbn
  654. # International Standard Book Number 10
  655. This validates that a string value contains a valid isbn10 value.
  656. Usage: isbn10
  657. # International Standard Book Number 13
  658. This validates that a string value contains a valid isbn13 value.
  659. Usage: isbn13
  660. # Universally Unique Identifier UUID
  661. This validates that a string value contains a valid UUID. Uppercase UUID values will not pass - use `uuid_rfc4122` instead.
  662. Usage: uuid
  663. # Universally Unique Identifier UUID v3
  664. This validates that a string value contains a valid version 3 UUID. Uppercase UUID values will not pass - use `uuid3_rfc4122` instead.
  665. Usage: uuid3
  666. # Universally Unique Identifier UUID v4
  667. This validates that a string value contains a valid version 4 UUID. Uppercase UUID values will not pass - use `uuid4_rfc4122` instead.
  668. Usage: uuid4
  669. # Universally Unique Identifier UUID v5
  670. This validates that a string value contains a valid version 5 UUID. Uppercase UUID values will not pass - use `uuid5_rfc4122` instead.
  671. Usage: uuid5
  672. # Universally Unique Lexicographically Sortable Identifier ULID
  673. This validates that a string value contains a valid ULID value.
  674. Usage: ulid
  675. # ASCII
  676. This validates that a string value contains only ASCII characters.
  677. NOTE: if the string is blank, this validates as true.
  678. Usage: ascii
  679. # Printable ASCII
  680. This validates that a string value contains only printable ASCII characters.
  681. NOTE: if the string is blank, this validates as true.
  682. Usage: printascii
  683. # Multi-Byte Characters
  684. This validates that a string value contains one or more multibyte characters.
  685. NOTE: if the string is blank, this validates as true.
  686. Usage: multibyte
  687. # Data URL
  688. This validates that a string value contains a valid DataURI.
  689. NOTE: this will also validate that the data portion is valid base64
  690. Usage: datauri
  691. # Latitude
  692. This validates that a string value contains a valid latitude.
  693. Usage: latitude
  694. # Longitude
  695. This validates that a string value contains a valid longitude.
  696. Usage: longitude
  697. # Employeer Identification Number EIN
  698. This validates that a string value contains a valid U.S. Employer Identification Number.
  699. Usage: ein
  700. # Social Security Number SSN
  701. This validates that a string value contains a valid U.S. Social Security Number.
  702. Usage: ssn
  703. # Internet Protocol Address IP
  704. This validates that a string value contains a valid IP Address.
  705. Usage: ip
  706. # Internet Protocol Address IPv4
  707. This validates that a string value contains a valid v4 IP Address.
  708. Usage: ipv4
  709. # Internet Protocol Address IPv6
  710. This validates that a string value contains a valid v6 IP Address.
  711. Usage: ipv6
  712. # Classless Inter-Domain Routing CIDR
  713. This validates that a string value contains a valid CIDR Address.
  714. Usage: cidr
  715. # Classless Inter-Domain Routing CIDRv4
  716. This validates that a string value contains a valid v4 CIDR Address.
  717. Usage: cidrv4
  718. # Classless Inter-Domain Routing CIDRv6
  719. This validates that a string value contains a valid v6 CIDR Address.
  720. Usage: cidrv6
  721. # Transmission Control Protocol Address TCP
  722. This validates that a string value contains a valid resolvable TCP Address.
  723. Usage: tcp_addr
  724. # Transmission Control Protocol Address TCPv4
  725. This validates that a string value contains a valid resolvable v4 TCP Address.
  726. Usage: tcp4_addr
  727. # Transmission Control Protocol Address TCPv6
  728. This validates that a string value contains a valid resolvable v6 TCP Address.
  729. Usage: tcp6_addr
  730. # User Datagram Protocol Address UDP
  731. This validates that a string value contains a valid resolvable UDP Address.
  732. Usage: udp_addr
  733. # User Datagram Protocol Address UDPv4
  734. This validates that a string value contains a valid resolvable v4 UDP Address.
  735. Usage: udp4_addr
  736. # User Datagram Protocol Address UDPv6
  737. This validates that a string value contains a valid resolvable v6 UDP Address.
  738. Usage: udp6_addr
  739. # Internet Protocol Address IP
  740. This validates that a string value contains a valid resolvable IP Address.
  741. Usage: ip_addr
  742. # Internet Protocol Address IPv4
  743. This validates that a string value contains a valid resolvable v4 IP Address.
  744. Usage: ip4_addr
  745. # Internet Protocol Address IPv6
  746. This validates that a string value contains a valid resolvable v6 IP Address.
  747. Usage: ip6_addr
  748. # Unix domain socket end point Address
  749. This validates that a string value contains a valid Unix Address.
  750. Usage: unix_addr
  751. # Media Access Control Address MAC
  752. This validates that a string value contains a valid MAC Address.
  753. Usage: mac
  754. Note: See Go's ParseMAC for accepted formats and types:
  755. http://golang.org/src/net/mac.go?s=866:918#L29
  756. # Hostname RFC 952
  757. This validates that a string value is a valid Hostname according to RFC 952 https://tools.ietf.org/html/rfc952
  758. Usage: hostname
  759. # Hostname RFC 1123
  760. This validates that a string value is a valid Hostname according to RFC 1123 https://tools.ietf.org/html/rfc1123
  761. Usage: hostname_rfc1123 or if you want to continue to use 'hostname' in your tags, create an alias.
  762. Full Qualified Domain Name (FQDN)
  763. This validates that a string value contains a valid FQDN.
  764. Usage: fqdn
  765. # HTML Tags
  766. This validates that a string value appears to be an HTML element tag
  767. including those described at https://developer.mozilla.org/en-US/docs/Web/HTML/Element
  768. Usage: html
  769. # HTML Encoded
  770. This validates that a string value is a proper character reference in decimal
  771. or hexadecimal format
  772. Usage: html_encoded
  773. # URL Encoded
  774. This validates that a string value is percent-encoded (URL encoded) according
  775. to https://tools.ietf.org/html/rfc3986#section-2.1
  776. Usage: url_encoded
  777. # Directory
  778. This validates that a string value contains a valid directory and that
  779. it exists on the machine.
  780. This is done using os.Stat, which is a platform independent function.
  781. Usage: dir
  782. # Directory Path
  783. This validates that a string value contains a valid directory but does
  784. not validate the existence of that directory.
  785. This is done using os.Stat, which is a platform independent function.
  786. It is safest to suffix the string with os.PathSeparator if the directory
  787. may not exist at the time of validation.
  788. Usage: dirpath
  789. # HostPort
  790. This validates that a string value contains a valid DNS hostname and port that
  791. can be used to validate fields typically passed to sockets and connections.
  792. Usage: hostname_port
  793. # Datetime
  794. This validates that a string value is a valid datetime based on the supplied datetime format.
  795. Supplied format must match the official Go time format layout as documented in https://golang.org/pkg/time/
  796. Usage: datetime=2006-01-02
  797. # Iso3166-1 alpha-2
  798. This validates that a string value is a valid country code based on iso3166-1 alpha-2 standard.
  799. see: https://www.iso.org/iso-3166-country-codes.html
  800. Usage: iso3166_1_alpha2
  801. # Iso3166-1 alpha-3
  802. This validates that a string value is a valid country code based on iso3166-1 alpha-3 standard.
  803. see: https://www.iso.org/iso-3166-country-codes.html
  804. Usage: iso3166_1_alpha3
  805. # Iso3166-1 alpha-numeric
  806. This validates that a string value is a valid country code based on iso3166-1 alpha-numeric standard.
  807. see: https://www.iso.org/iso-3166-country-codes.html
  808. Usage: iso3166_1_alpha3
  809. # BCP 47 Language Tag
  810. This validates that a string value is a valid BCP 47 language tag, as parsed by language.Parse.
  811. More information on https://pkg.go.dev/golang.org/x/text/language
  812. Usage: bcp47_language_tag
  813. BIC (SWIFT code)
  814. This validates that a string value is a valid Business Identifier Code (SWIFT code), defined in ISO 9362.
  815. More information on https://www.iso.org/standard/60390.html
  816. Usage: bic
  817. # RFC 1035 label
  818. This validates that a string value is a valid dns RFC 1035 label, defined in RFC 1035.
  819. More information on https://datatracker.ietf.org/doc/html/rfc1035
  820. Usage: dns_rfc1035_label
  821. # TimeZone
  822. This validates that a string value is a valid time zone based on the time zone database present on the system.
  823. Although empty value and Local value are allowed by time.LoadLocation golang function, they are not allowed by this validator.
  824. More information on https://golang.org/pkg/time/#LoadLocation
  825. Usage: timezone
  826. # Semantic Version
  827. This validates that a string value is a valid semver version, defined in Semantic Versioning 2.0.0.
  828. More information on https://semver.org/
  829. Usage: semver
  830. # CVE Identifier
  831. This validates that a string value is a valid cve id, defined in cve mitre.
  832. More information on https://cve.mitre.org/
  833. Usage: cve
  834. # Credit Card
  835. This validates that a string value contains a valid credit card number using Luhn algorithm.
  836. Usage: credit_card
  837. # Luhn Checksum
  838. Usage: luhn_checksum
  839. This validates that a string or (u)int value contains a valid checksum using the Luhn algorithm.
  840. # MongoDB
  841. This validates that a string is a valid 24 character hexadecimal string or valid connection string.
  842. Usage: mongodb
  843. mongodb_connection_string
  844. Example:
  845. type Test struct {
  846. ObjectIdField string `validate:"mongodb"`
  847. ConnectionStringField string `validate:"mongodb_connection_string"`
  848. }
  849. # Cron
  850. This validates that a string value contains a valid cron expression.
  851. Usage: cron
  852. # SpiceDb ObjectID/Permission/Object Type
  853. This validates that a string is valid for use with SpiceDb for the indicated purpose. If no purpose is given, a purpose of 'id' is assumed.
  854. Usage: spicedb=id|permission|type
  855. # Alias Validators and Tags
  856. Alias Validators and Tags
  857. NOTE: When returning an error, the tag returned in "FieldError" will be
  858. the alias tag unless the dive tag is part of the alias. Everything after the
  859. dive tag is not reported as the alias tag. Also, the "ActualTag" in the before
  860. case will be the actual tag within the alias that failed.
  861. Here is a list of the current built in alias tags:
  862. "iscolor"
  863. alias is "hexcolor|rgb|rgba|hsl|hsla" (Usage: iscolor)
  864. "country_code"
  865. alias is "iso3166_1_alpha2|iso3166_1_alpha3|iso3166_1_alpha_numeric" (Usage: country_code)
  866. Validator notes:
  867. regex
  868. a regex validator won't be added because commas and = signs can be part
  869. of a regex which conflict with the validation definitions. Although
  870. workarounds can be made, they take away from using pure regex's.
  871. Furthermore it's quick and dirty but the regex's become harder to
  872. maintain and are not reusable, so it's as much a programming philosophy
  873. as anything.
  874. In place of this new validator functions should be created; a regex can
  875. be used within the validator function and even be precompiled for better
  876. efficiency within regexes.go.
  877. And the best reason, you can submit a pull request and we can keep on
  878. adding to the validation library of this package!
  879. # Non standard validators
  880. A collection of validation rules that are frequently needed but are more
  881. complex than the ones found in the baked in validators.
  882. A non standard validator must be registered manually like you would
  883. with your own custom validation functions.
  884. Example of registration and use:
  885. type Test struct {
  886. TestField string `validate:"yourtag"`
  887. }
  888. t := &Test{
  889. TestField: "Test"
  890. }
  891. validate := validator.New()
  892. validate.RegisterValidation("yourtag", validators.NotBlank)
  893. Here is a list of the current non standard validators:
  894. NotBlank
  895. This validates that the value is not blank or with length zero.
  896. For strings ensures they do not contain only spaces. For channels, maps, slices and arrays
  897. ensures they don't have zero length. For others, a non empty value is required.
  898. Usage: notblank
  899. # Panics
  900. This package panics when bad input is provided, this is by design, bad code like
  901. that should not make it to production.
  902. type Test struct {
  903. TestField string `validate:"nonexistantfunction=1"`
  904. }
  905. t := &Test{
  906. TestField: "Test"
  907. }
  908. validate.Struct(t) // this will panic
  909. */
  910. package validator