doc.go 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483
  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 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.
  329. Usage: oneof=red green
  330. oneof='red green' 'blue yellow'
  331. oneof=5 7 9
  332. # Greater Than
  333. For numbers, this will ensure that the value is greater than the
  334. parameter given. For strings, it checks that the string length
  335. is greater than that number of characters. For slices, arrays
  336. and maps it validates the number of items.
  337. Example #1
  338. Usage: gt=10
  339. Example #2 (time.Time)
  340. For time.Time ensures the time value is greater than time.Now.UTC().
  341. Usage: gt
  342. Example #3 (time.Duration)
  343. For time.Duration, gt will ensure that the value is greater than the duration
  344. given in the parameter.
  345. Usage: gt=1h30m
  346. # Greater Than or Equal
  347. Same as 'min' above. Kept both to make terminology with 'len' easier.
  348. Example #1
  349. Usage: gte=10
  350. Example #2 (time.Time)
  351. For time.Time ensures the time value is greater than or equal to time.Now.UTC().
  352. Usage: gte
  353. Example #3 (time.Duration)
  354. For time.Duration, gte will ensure that the value is greater than or equal to
  355. the duration given in the parameter.
  356. Usage: gte=1h30m
  357. # Less Than
  358. For numbers, this will ensure that the value is less than the parameter given.
  359. For strings, it checks that the string length is less than that number of
  360. characters. For slices, arrays, and maps it validates the number of items.
  361. Example #1
  362. Usage: lt=10
  363. Example #2 (time.Time)
  364. For time.Time ensures the time value is less than time.Now.UTC().
  365. Usage: lt
  366. Example #3 (time.Duration)
  367. For time.Duration, lt will ensure that the value is less than the duration given
  368. in the parameter.
  369. Usage: lt=1h30m
  370. # Less Than or Equal
  371. Same as 'max' above. Kept both to make terminology with 'len' easier.
  372. Example #1
  373. Usage: lte=10
  374. Example #2 (time.Time)
  375. For time.Time ensures the time value is less than or equal to time.Now.UTC().
  376. Usage: lte
  377. Example #3 (time.Duration)
  378. For time.Duration, lte will ensure that the value is less than or equal to the
  379. duration given in the parameter.
  380. Usage: lte=1h30m
  381. # Field Equals Another Field
  382. This will validate the field value against another fields value either within
  383. a struct or passed in field.
  384. Example #1:
  385. // Validation on Password field using:
  386. Usage: eqfield=ConfirmPassword
  387. Example #2:
  388. // Validating by field:
  389. validate.VarWithValue(password, confirmpassword, "eqfield")
  390. Field Equals Another Field (relative)
  391. This does the same as eqfield except that it validates the field provided relative
  392. to the top level struct.
  393. Usage: eqcsfield=InnerStructField.Field)
  394. # Field Does Not Equal Another Field
  395. This will validate the field value against another fields value either within
  396. a struct or passed in field.
  397. Examples:
  398. // Confirm two colors are not the same:
  399. //
  400. // Validation on Color field:
  401. Usage: nefield=Color2
  402. // Validating by field:
  403. validate.VarWithValue(color1, color2, "nefield")
  404. Field Does Not Equal Another Field (relative)
  405. This does the same as nefield except that it validates the field provided
  406. relative to the top level struct.
  407. Usage: necsfield=InnerStructField.Field
  408. # Field Greater Than Another Field
  409. Only valid for Numbers, time.Duration and time.Time types, this will validate
  410. the field value against another fields value either within a struct or passed in
  411. field. usage examples are for validation of a Start and End date:
  412. Example #1:
  413. // Validation on End field using:
  414. validate.Struct Usage(gtfield=Start)
  415. Example #2:
  416. // Validating by field:
  417. validate.VarWithValue(start, end, "gtfield")
  418. # Field Greater Than Another Relative Field
  419. This does the same as gtfield except that it validates the field provided
  420. relative to the top level struct.
  421. Usage: gtcsfield=InnerStructField.Field
  422. # Field Greater Than or Equal To Another Field
  423. Only valid for Numbers, time.Duration and time.Time types, this will validate
  424. the field value against another fields value either within a struct or passed in
  425. field. usage examples are for validation of a Start and End date:
  426. Example #1:
  427. // Validation on End field using:
  428. validate.Struct Usage(gtefield=Start)
  429. Example #2:
  430. // Validating by field:
  431. validate.VarWithValue(start, end, "gtefield")
  432. # Field Greater Than or Equal To Another Relative Field
  433. This does the same as gtefield except that it validates the field provided relative
  434. to the top level struct.
  435. Usage: gtecsfield=InnerStructField.Field
  436. # Less Than Another Field
  437. Only valid for Numbers, time.Duration and time.Time types, this will validate
  438. the field value against another fields value either within a struct or passed in
  439. field. usage examples are for validation of a Start and End date:
  440. Example #1:
  441. // Validation on End field using:
  442. validate.Struct Usage(ltfield=Start)
  443. Example #2:
  444. // Validating by field:
  445. validate.VarWithValue(start, end, "ltfield")
  446. # Less Than Another Relative Field
  447. This does the same as ltfield except that it validates the field provided relative
  448. to the top level struct.
  449. Usage: ltcsfield=InnerStructField.Field
  450. # Less Than or Equal To Another Field
  451. Only valid for Numbers, time.Duration and time.Time types, this will validate
  452. the field value against another fields value either within a struct or passed in
  453. field. usage examples are for validation of a Start and End date:
  454. Example #1:
  455. // Validation on End field using:
  456. validate.Struct Usage(ltefield=Start)
  457. Example #2:
  458. // Validating by field:
  459. validate.VarWithValue(start, end, "ltefield")
  460. # Less Than or Equal To Another Relative Field
  461. This does the same as ltefield except that it validates the field provided relative
  462. to the top level struct.
  463. Usage: ltecsfield=InnerStructField.Field
  464. # Field Contains Another Field
  465. This does the same as contains except for struct fields. It should only be used
  466. with string types. See the behavior of reflect.Value.String() for behavior on
  467. other types.
  468. Usage: containsfield=InnerStructField.Field
  469. # Field Excludes Another Field
  470. This does the same as excludes except for struct fields. It should only be used
  471. with string types. See the behavior of reflect.Value.String() for behavior on
  472. other types.
  473. Usage: excludesfield=InnerStructField.Field
  474. # Unique
  475. For arrays & slices, unique will ensure that there are no duplicates.
  476. For maps, unique will ensure that there are no duplicate values.
  477. For slices of struct, unique will ensure that there are no duplicate values
  478. in a field of the struct specified via a parameter.
  479. // For arrays, slices, and maps:
  480. Usage: unique
  481. // For slices of struct:
  482. Usage: unique=field
  483. # Alpha Only
  484. This validates that a string value contains ASCII alpha characters only
  485. Usage: alpha
  486. # Alphanumeric
  487. This validates that a string value contains ASCII alphanumeric characters only
  488. Usage: alphanum
  489. # Alpha Unicode
  490. This validates that a string value contains unicode alpha characters only
  491. Usage: alphaunicode
  492. # Alphanumeric Unicode
  493. This validates that a string value contains unicode alphanumeric characters only
  494. Usage: alphanumunicode
  495. # Boolean
  496. This validates that a string value can successfully be parsed into a boolean with strconv.ParseBool
  497. Usage: boolean
  498. # Number
  499. This validates that a string value contains number values only.
  500. For integers or float it returns true.
  501. Usage: number
  502. # Numeric
  503. This validates that a string value contains a basic numeric value.
  504. basic excludes exponents etc...
  505. for integers or float it returns true.
  506. Usage: numeric
  507. # Hexadecimal String
  508. This validates that a string value contains a valid hexadecimal.
  509. Usage: hexadecimal
  510. # Hexcolor String
  511. This validates that a string value contains a valid hex color including
  512. hashtag (#)
  513. Usage: hexcolor
  514. # Lowercase String
  515. This validates that a string value contains only lowercase characters. An empty string is not a valid lowercase string.
  516. Usage: lowercase
  517. # Uppercase String
  518. This validates that a string value contains only uppercase characters. An empty string is not a valid uppercase string.
  519. Usage: uppercase
  520. # RGB String
  521. This validates that a string value contains a valid rgb color
  522. Usage: rgb
  523. # RGBA String
  524. This validates that a string value contains a valid rgba color
  525. Usage: rgba
  526. # HSL String
  527. This validates that a string value contains a valid hsl color
  528. Usage: hsl
  529. # HSLA String
  530. This validates that a string value contains a valid hsla color
  531. Usage: hsla
  532. # E.164 Phone Number String
  533. This validates that a string value contains a valid E.164 Phone number
  534. https://en.wikipedia.org/wiki/E.164 (ex. +1123456789)
  535. Usage: e164
  536. # E-mail String
  537. This validates that a string value contains a valid email
  538. This may not conform to all possibilities of any rfc standard, but neither
  539. does any email provider accept all possibilities.
  540. Usage: email
  541. # JSON String
  542. This validates that a string value is valid JSON
  543. Usage: json
  544. # JWT String
  545. This validates that a string value is a valid JWT
  546. Usage: jwt
  547. # File
  548. This validates that a string value contains a valid file path and that
  549. the file exists on the machine.
  550. This is done using os.Stat, which is a platform independent function.
  551. Usage: file
  552. # Image path
  553. This validates that a string value contains a valid file path and that
  554. the file exists on the machine and is an image.
  555. This is done using os.Stat and github.com/gabriel-vasile/mimetype
  556. Usage: image
  557. # File Path
  558. This validates that a string value contains a valid file path but does not
  559. validate the existence of that file.
  560. This is done using os.Stat, which is a platform independent function.
  561. Usage: filepath
  562. # URL String
  563. This validates that a string value contains a valid url
  564. This will accept any url the golang request uri accepts but must contain
  565. a schema for example http:// or rtmp://
  566. Usage: url
  567. # URI String
  568. This validates that a string value contains a valid uri
  569. This will accept any uri the golang request uri accepts
  570. Usage: uri
  571. # Urn RFC 2141 String
  572. This validataes that a string value contains a valid URN
  573. according to the RFC 2141 spec.
  574. Usage: urn_rfc2141
  575. # Base32 String
  576. This validates that a string value contains a valid bas324 value.
  577. Although an empty string is valid base32 this will report an empty string
  578. as an error, if you wish to accept an empty string as valid you can use
  579. this with the omitempty tag.
  580. Usage: base32
  581. # Base64 String
  582. This validates that a string value contains a valid base64 value.
  583. Although an empty string is valid base64 this will report an empty string
  584. as an error, if you wish to accept an empty string as valid you can use
  585. this with the omitempty tag.
  586. Usage: base64
  587. # Base64URL String
  588. This validates that a string value contains a valid base64 URL safe value
  589. according the RFC4648 spec.
  590. Although an empty string is a valid base64 URL safe value, this will report
  591. an empty string as an error, if you wish to accept an empty string as valid
  592. you can use this with the omitempty tag.
  593. Usage: base64url
  594. # Base64RawURL String
  595. This validates that a string value contains a valid base64 URL safe value,
  596. but without = padding, according the RFC4648 spec, section 3.2.
  597. Although an empty string is a valid base64 URL safe value, this will report
  598. an empty string as an error, if you wish to accept an empty string as valid
  599. you can use this with the omitempty tag.
  600. Usage: base64url
  601. # Bitcoin Address
  602. This validates that a string value contains a valid bitcoin address.
  603. The format of the string is checked to ensure it matches one of the three formats
  604. P2PKH, P2SH and performs checksum validation.
  605. Usage: btc_addr
  606. Bitcoin Bech32 Address (segwit)
  607. This validates that a string value contains a valid bitcoin Bech32 address as defined
  608. by bip-0173 (https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki)
  609. Special thanks to Pieter Wuille for providng reference implementations.
  610. Usage: btc_addr_bech32
  611. # Ethereum Address
  612. This validates that a string value contains a valid ethereum address.
  613. The format of the string is checked to ensure it matches the standard Ethereum address format.
  614. Usage: eth_addr
  615. # Contains
  616. This validates that a string value contains the substring value.
  617. Usage: contains=@
  618. # Contains Any
  619. This validates that a string value contains any Unicode code points
  620. in the substring value.
  621. Usage: containsany=!@#?
  622. # Contains Rune
  623. This validates that a string value contains the supplied rune value.
  624. Usage: containsrune=@
  625. # Excludes
  626. This validates that a string value does not contain the substring value.
  627. Usage: excludes=@
  628. # Excludes All
  629. This validates that a string value does not contain any Unicode code
  630. points in the substring value.
  631. Usage: excludesall=!@#?
  632. # Excludes Rune
  633. This validates that a string value does not contain the supplied rune value.
  634. Usage: excludesrune=@
  635. # Starts With
  636. This validates that a string value starts with the supplied string value
  637. Usage: startswith=hello
  638. # Ends With
  639. This validates that a string value ends with the supplied string value
  640. Usage: endswith=goodbye
  641. # Does Not Start With
  642. This validates that a string value does not start with the supplied string value
  643. Usage: startsnotwith=hello
  644. # Does Not End With
  645. This validates that a string value does not end with the supplied string value
  646. Usage: endsnotwith=goodbye
  647. # International Standard Book Number
  648. This validates that a string value contains a valid isbn10 or isbn13 value.
  649. Usage: isbn
  650. # International Standard Book Number 10
  651. This validates that a string value contains a valid isbn10 value.
  652. Usage: isbn10
  653. # International Standard Book Number 13
  654. This validates that a string value contains a valid isbn13 value.
  655. Usage: isbn13
  656. # Universally Unique Identifier UUID
  657. This validates that a string value contains a valid UUID. Uppercase UUID values will not pass - use `uuid_rfc4122` instead.
  658. Usage: uuid
  659. # Universally Unique Identifier UUID v3
  660. This validates that a string value contains a valid version 3 UUID. Uppercase UUID values will not pass - use `uuid3_rfc4122` instead.
  661. Usage: uuid3
  662. # Universally Unique Identifier UUID v4
  663. This validates that a string value contains a valid version 4 UUID. Uppercase UUID values will not pass - use `uuid4_rfc4122` instead.
  664. Usage: uuid4
  665. # Universally Unique Identifier UUID v5
  666. This validates that a string value contains a valid version 5 UUID. Uppercase UUID values will not pass - use `uuid5_rfc4122` instead.
  667. Usage: uuid5
  668. # Universally Unique Lexicographically Sortable Identifier ULID
  669. This validates that a string value contains a valid ULID value.
  670. Usage: ulid
  671. # ASCII
  672. This validates that a string value contains only ASCII characters.
  673. NOTE: if the string is blank, this validates as true.
  674. Usage: ascii
  675. # Printable ASCII
  676. This validates that a string value contains only printable ASCII characters.
  677. NOTE: if the string is blank, this validates as true.
  678. Usage: printascii
  679. # Multi-Byte Characters
  680. This validates that a string value contains one or more multibyte characters.
  681. NOTE: if the string is blank, this validates as true.
  682. Usage: multibyte
  683. # Data URL
  684. This validates that a string value contains a valid DataURI.
  685. NOTE: this will also validate that the data portion is valid base64
  686. Usage: datauri
  687. # Latitude
  688. This validates that a string value contains a valid latitude.
  689. Usage: latitude
  690. # Longitude
  691. This validates that a string value contains a valid longitude.
  692. Usage: longitude
  693. # Social Security Number SSN
  694. This validates that a string value contains a valid U.S. Social Security Number.
  695. Usage: ssn
  696. # Internet Protocol Address IP
  697. This validates that a string value contains a valid IP Address.
  698. Usage: ip
  699. # Internet Protocol Address IPv4
  700. This validates that a string value contains a valid v4 IP Address.
  701. Usage: ipv4
  702. # Internet Protocol Address IPv6
  703. This validates that a string value contains a valid v6 IP Address.
  704. Usage: ipv6
  705. # Classless Inter-Domain Routing CIDR
  706. This validates that a string value contains a valid CIDR Address.
  707. Usage: cidr
  708. # Classless Inter-Domain Routing CIDRv4
  709. This validates that a string value contains a valid v4 CIDR Address.
  710. Usage: cidrv4
  711. # Classless Inter-Domain Routing CIDRv6
  712. This validates that a string value contains a valid v6 CIDR Address.
  713. Usage: cidrv6
  714. # Transmission Control Protocol Address TCP
  715. This validates that a string value contains a valid resolvable TCP Address.
  716. Usage: tcp_addr
  717. # Transmission Control Protocol Address TCPv4
  718. This validates that a string value contains a valid resolvable v4 TCP Address.
  719. Usage: tcp4_addr
  720. # Transmission Control Protocol Address TCPv6
  721. This validates that a string value contains a valid resolvable v6 TCP Address.
  722. Usage: tcp6_addr
  723. # User Datagram Protocol Address UDP
  724. This validates that a string value contains a valid resolvable UDP Address.
  725. Usage: udp_addr
  726. # User Datagram Protocol Address UDPv4
  727. This validates that a string value contains a valid resolvable v4 UDP Address.
  728. Usage: udp4_addr
  729. # User Datagram Protocol Address UDPv6
  730. This validates that a string value contains a valid resolvable v6 UDP Address.
  731. Usage: udp6_addr
  732. # Internet Protocol Address IP
  733. This validates that a string value contains a valid resolvable IP Address.
  734. Usage: ip_addr
  735. # Internet Protocol Address IPv4
  736. This validates that a string value contains a valid resolvable v4 IP Address.
  737. Usage: ip4_addr
  738. # Internet Protocol Address IPv6
  739. This validates that a string value contains a valid resolvable v6 IP Address.
  740. Usage: ip6_addr
  741. # Unix domain socket end point Address
  742. This validates that a string value contains a valid Unix Address.
  743. Usage: unix_addr
  744. # Media Access Control Address MAC
  745. This validates that a string value contains a valid MAC Address.
  746. Usage: mac
  747. Note: See Go's ParseMAC for accepted formats and types:
  748. http://golang.org/src/net/mac.go?s=866:918#L29
  749. # Hostname RFC 952
  750. This validates that a string value is a valid Hostname according to RFC 952 https://tools.ietf.org/html/rfc952
  751. Usage: hostname
  752. # Hostname RFC 1123
  753. This validates that a string value is a valid Hostname according to RFC 1123 https://tools.ietf.org/html/rfc1123
  754. Usage: hostname_rfc1123 or if you want to continue to use 'hostname' in your tags, create an alias.
  755. Full Qualified Domain Name (FQDN)
  756. This validates that a string value contains a valid FQDN.
  757. Usage: fqdn
  758. # HTML Tags
  759. This validates that a string value appears to be an HTML element tag
  760. including those described at https://developer.mozilla.org/en-US/docs/Web/HTML/Element
  761. Usage: html
  762. # HTML Encoded
  763. This validates that a string value is a proper character reference in decimal
  764. or hexadecimal format
  765. Usage: html_encoded
  766. # URL Encoded
  767. This validates that a string value is percent-encoded (URL encoded) according
  768. to https://tools.ietf.org/html/rfc3986#section-2.1
  769. Usage: url_encoded
  770. # Directory
  771. This validates that a string value contains a valid directory and that
  772. it exists on the machine.
  773. This is done using os.Stat, which is a platform independent function.
  774. Usage: dir
  775. # Directory Path
  776. This validates that a string value contains a valid directory but does
  777. not validate the existence of that directory.
  778. This is done using os.Stat, which is a platform independent function.
  779. It is safest to suffix the string with os.PathSeparator if the directory
  780. may not exist at the time of validation.
  781. Usage: dirpath
  782. # HostPort
  783. This validates that a string value contains a valid DNS hostname and port that
  784. can be used to valiate fields typically passed to sockets and connections.
  785. Usage: hostname_port
  786. # Datetime
  787. This validates that a string value is a valid datetime based on the supplied datetime format.
  788. Supplied format must match the official Go time format layout as documented in https://golang.org/pkg/time/
  789. Usage: datetime=2006-01-02
  790. # Iso3166-1 alpha-2
  791. This validates that a string value is a valid country code based on iso3166-1 alpha-2 standard.
  792. see: https://www.iso.org/iso-3166-country-codes.html
  793. Usage: iso3166_1_alpha2
  794. # Iso3166-1 alpha-3
  795. This validates that a string value is a valid country code based on iso3166-1 alpha-3 standard.
  796. see: https://www.iso.org/iso-3166-country-codes.html
  797. Usage: iso3166_1_alpha3
  798. # Iso3166-1 alpha-numeric
  799. This validates that a string value is a valid country code based on iso3166-1 alpha-numeric standard.
  800. see: https://www.iso.org/iso-3166-country-codes.html
  801. Usage: iso3166_1_alpha3
  802. # BCP 47 Language Tag
  803. This validates that a string value is a valid BCP 47 language tag, as parsed by language.Parse.
  804. More information on https://pkg.go.dev/golang.org/x/text/language
  805. Usage: bcp47_language_tag
  806. BIC (SWIFT code)
  807. This validates that a string value is a valid Business Identifier Code (SWIFT code), defined in ISO 9362.
  808. More information on https://www.iso.org/standard/60390.html
  809. Usage: bic
  810. # RFC 1035 label
  811. This validates that a string value is a valid dns RFC 1035 label, defined in RFC 1035.
  812. More information on https://datatracker.ietf.org/doc/html/rfc1035
  813. Usage: dns_rfc1035_label
  814. # TimeZone
  815. This validates that a string value is a valid time zone based on the time zone database present on the system.
  816. Although empty value and Local value are allowed by time.LoadLocation golang function, they are not allowed by this validator.
  817. More information on https://golang.org/pkg/time/#LoadLocation
  818. Usage: timezone
  819. # Semantic Version
  820. This validates that a string value is a valid semver version, defined in Semantic Versioning 2.0.0.
  821. More information on https://semver.org/
  822. Usage: semver
  823. # CVE Identifier
  824. This validates that a string value is a valid cve id, defined in cve mitre.
  825. More information on https://cve.mitre.org/
  826. Usage: cve
  827. # Credit Card
  828. This validates that a string value contains a valid credit card number using Luhn algorithm.
  829. Usage: credit_card
  830. # Luhn Checksum
  831. Usage: luhn_checksum
  832. This validates that a string or (u)int value contains a valid checksum using the Luhn algorithm.
  833. # MongoDb ObjectID
  834. This validates that a string is a valid 24 character hexadecimal string.
  835. Usage: mongodb
  836. # Cron
  837. This validates that a string value contains a valid cron expression.
  838. Usage: cron
  839. # SpiceDb ObjectID/Permission/Object Type
  840. 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.
  841. Usage: spicedb=id|permission|type
  842. # Alias Validators and Tags
  843. Alias Validators and Tags
  844. NOTE: When returning an error, the tag returned in "FieldError" will be
  845. the alias tag unless the dive tag is part of the alias. Everything after the
  846. dive tag is not reported as the alias tag. Also, the "ActualTag" in the before
  847. case will be the actual tag within the alias that failed.
  848. Here is a list of the current built in alias tags:
  849. "iscolor"
  850. alias is "hexcolor|rgb|rgba|hsl|hsla" (Usage: iscolor)
  851. "country_code"
  852. alias is "iso3166_1_alpha2|iso3166_1_alpha3|iso3166_1_alpha_numeric" (Usage: country_code)
  853. Validator notes:
  854. regex
  855. a regex validator won't be added because commas and = signs can be part
  856. of a regex which conflict with the validation definitions. Although
  857. workarounds can be made, they take away from using pure regex's.
  858. Furthermore it's quick and dirty but the regex's become harder to
  859. maintain and are not reusable, so it's as much a programming philosophy
  860. as anything.
  861. In place of this new validator functions should be created; a regex can
  862. be used within the validator function and even be precompiled for better
  863. efficiency within regexes.go.
  864. And the best reason, you can submit a pull request and we can keep on
  865. adding to the validation library of this package!
  866. # Non standard validators
  867. A collection of validation rules that are frequently needed but are more
  868. complex than the ones found in the baked in validators.
  869. A non standard validator must be registered manually like you would
  870. with your own custom validation functions.
  871. Example of registration and use:
  872. type Test struct {
  873. TestField string `validate:"yourtag"`
  874. }
  875. t := &Test{
  876. TestField: "Test"
  877. }
  878. validate := validator.New()
  879. validate.RegisterValidation("yourtag", validators.NotBlank)
  880. Here is a list of the current non standard validators:
  881. NotBlank
  882. This validates that the value is not blank or with length zero.
  883. For strings ensures they do not contain only spaces. For channels, maps, slices and arrays
  884. ensures they don't have zero length. For others, a non empty value is required.
  885. Usage: notblank
  886. # Panics
  887. This package panics when bad input is provided, this is by design, bad code like
  888. that should not make it to production.
  889. type Test struct {
  890. TestField string `validate:"nonexistantfunction=1"`
  891. }
  892. t := &Test{
  893. TestField: "Test"
  894. }
  895. validate.Struct(t) // this will panic
  896. */
  897. package validator