doc.go 34 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342
  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 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. Dive
  139. This tells the validator to dive into a slice, array or map and validate that
  140. level of the slice, array or map with the validation tags that follow.
  141. Multidimensional nesting is also supported, each level you wish to dive will
  142. require another dive tag. dive has some sub-tags, 'keys' & 'endkeys', please see
  143. the Keys & EndKeys section just below.
  144. Usage: dive
  145. Example #1
  146. [][]string with validation tag "gt=0,dive,len=1,dive,required"
  147. // gt=0 will be applied to []
  148. // len=1 will be applied to []string
  149. // required will be applied to string
  150. Example #2
  151. [][]string with validation tag "gt=0,dive,dive,required"
  152. // gt=0 will be applied to []
  153. // []string will be spared validation
  154. // required will be applied to string
  155. Keys & EndKeys
  156. These are to be used together directly after the dive tag and tells the validator
  157. that anything between 'keys' and 'endkeys' applies to the keys of a map and not the
  158. values; think of it like the 'dive' tag, but for map keys instead of values.
  159. Multidimensional nesting is also supported, each level you wish to validate will
  160. require another 'keys' and 'endkeys' tag. These tags are only valid for maps.
  161. Usage: dive,keys,othertagvalidation(s),endkeys,valuevalidationtags
  162. Example #1
  163. map[string]string with validation tag "gt=0,dive,keys,eg=1|eq=2,endkeys,required"
  164. // gt=0 will be applied to the map itself
  165. // eg=1|eq=2 will be applied to the map keys
  166. // required will be applied to map values
  167. Example #2
  168. map[[2]string]string with validation tag "gt=0,dive,keys,dive,eq=1|eq=2,endkeys,required"
  169. // gt=0 will be applied to the map itself
  170. // eg=1|eq=2 will be applied to each array element in the the map keys
  171. // required will be applied to map values
  172. Required
  173. This validates that the value is not the data types default zero value.
  174. For numbers ensures value is not zero. For strings ensures value is
  175. not "". For slices, maps, pointers, interfaces, channels and functions
  176. ensures the value is not nil.
  177. Usage: required
  178. Required If
  179. The field under validation must be present and not empty only if all
  180. the other specified fields are equal to the value following the specified
  181. field. For strings ensures value is not "". For slices, maps, pointers,
  182. interfaces, channels and functions ensures the value is not nil.
  183. Usage: required_if
  184. Examples:
  185. // require the field if the Field1 is equal to the parameter given:
  186. Usage: required_if=Field1 foobar
  187. // require the field if the Field1 and Field2 is equal to the value respectively:
  188. Usage: required_if=Field1 foo Field2 bar
  189. Required Unless
  190. The field under validation must be present and not empty unless all
  191. the other specified fields are equal to the value following the specified
  192. field. For strings ensures value is not "". For slices, maps, pointers,
  193. interfaces, channels and functions ensures the value is not nil.
  194. Usage: required_unless
  195. Examples:
  196. // require the field unless the Field1 is equal to the parameter given:
  197. Usage: required_unless=Field1 foobar
  198. // require the field unless the Field1 and Field2 is equal to the value respectively:
  199. Usage: required_unless=Field1 foo Field2 bar
  200. Required With
  201. The field under validation must be present and not empty only if any
  202. of the other specified fields are present. For strings ensures value is
  203. not "". For slices, maps, pointers, interfaces, channels and functions
  204. ensures the value is not nil.
  205. Usage: required_with
  206. Examples:
  207. // require the field if the Field1 is present:
  208. Usage: required_with=Field1
  209. // require the field if the Field1 or Field2 is present:
  210. Usage: required_with=Field1 Field2
  211. Required With All
  212. The field under validation must be present and not empty only if all
  213. of the other specified fields are present. For strings ensures value is
  214. not "". For slices, maps, pointers, interfaces, channels and functions
  215. ensures the value is not nil.
  216. Usage: required_with_all
  217. Example:
  218. // require the field if the Field1 and Field2 is present:
  219. Usage: required_with_all=Field1 Field2
  220. Required Without
  221. The field under validation must be present and not empty only when any
  222. of the other specified fields are not present. For strings ensures value is
  223. not "". For slices, maps, pointers, interfaces, channels and functions
  224. ensures the value is not nil.
  225. Usage: required_without
  226. Examples:
  227. // require the field if the Field1 is not present:
  228. Usage: required_without=Field1
  229. // require the field if the Field1 or Field2 is not present:
  230. Usage: required_without=Field1 Field2
  231. Required Without All
  232. The field under validation must be present and not empty only when all
  233. of the other specified fields are not present. For strings ensures value is
  234. not "". For slices, maps, pointers, interfaces, channels and functions
  235. ensures the value is not nil.
  236. Usage: required_without_all
  237. Example:
  238. // require the field if the Field1 and Field2 is not present:
  239. Usage: required_without_all=Field1 Field2
  240. Is Default
  241. This validates that the value is the default value and is almost the
  242. opposite of required.
  243. Usage: isdefault
  244. Length
  245. For numbers, length will ensure that the value is
  246. equal to the parameter given. For strings, it checks that
  247. the string length is exactly that number of characters. For slices,
  248. arrays, and maps, validates the number of items.
  249. Example #1
  250. Usage: len=10
  251. Example #2 (time.Duration)
  252. For time.Duration, len will ensure that the value is equal to the duration given
  253. in the parameter.
  254. Usage: len=1h30m
  255. Maximum
  256. For numbers, max will ensure that the value is
  257. less than or equal to the parameter given. For strings, it checks
  258. that the string length is at most that number of characters. For
  259. slices, arrays, and maps, validates the number of items.
  260. Example #1
  261. Usage: max=10
  262. Example #2 (time.Duration)
  263. For time.Duration, max will ensure that the value is less than or equal to the
  264. duration given in the parameter.
  265. Usage: max=1h30m
  266. Minimum
  267. For numbers, min will ensure that the value is
  268. greater or equal to the parameter given. For strings, it checks that
  269. the string length is at least that number of characters. For slices,
  270. arrays, and maps, validates the number of items.
  271. Example #1
  272. Usage: min=10
  273. Example #2 (time.Duration)
  274. For time.Duration, min will ensure that the value is greater than or equal to
  275. the duration given in the parameter.
  276. Usage: min=1h30m
  277. Equals
  278. For strings & numbers, eq will ensure that the value is
  279. equal to the parameter given. For slices, arrays, and maps,
  280. validates the number of items.
  281. Example #1
  282. Usage: eq=10
  283. Example #2 (time.Duration)
  284. For time.Duration, eq will ensure that the value is equal to the duration given
  285. in the parameter.
  286. Usage: eq=1h30m
  287. Not Equal
  288. For strings & numbers, ne will ensure that the value is not
  289. equal to the parameter given. For slices, arrays, and maps,
  290. validates the number of items.
  291. Example #1
  292. Usage: ne=10
  293. Example #2 (time.Duration)
  294. For time.Duration, ne will ensure that the value is not equal to the duration
  295. given in the parameter.
  296. Usage: ne=1h30m
  297. One Of
  298. For strings, ints, and uints, oneof will ensure that the value
  299. is one of the values in the parameter. The parameter should be
  300. a list of values separated by whitespace. Values may be
  301. strings or numbers. To match strings with spaces in them, include
  302. the target string between single quotes.
  303. Usage: oneof=red green
  304. oneof='red green' 'blue yellow'
  305. oneof=5 7 9
  306. Greater Than
  307. For numbers, this will ensure that the value is greater than the
  308. parameter given. For strings, it checks that the string length
  309. is greater than that number of characters. For slices, arrays
  310. and maps it validates the number of items.
  311. Example #1
  312. Usage: gt=10
  313. Example #2 (time.Time)
  314. For time.Time ensures the time value is greater than time.Now.UTC().
  315. Usage: gt
  316. Example #3 (time.Duration)
  317. For time.Duration, gt will ensure that the value is greater than the duration
  318. given in the parameter.
  319. Usage: gt=1h30m
  320. Greater Than or Equal
  321. Same as 'min' above. Kept both to make terminology with 'len' easier.
  322. Example #1
  323. Usage: gte=10
  324. Example #2 (time.Time)
  325. For time.Time ensures the time value is greater than or equal to time.Now.UTC().
  326. Usage: gte
  327. Example #3 (time.Duration)
  328. For time.Duration, gte will ensure that the value is greater than or equal to
  329. the duration given in the parameter.
  330. Usage: gte=1h30m
  331. Less Than
  332. For numbers, this will ensure that the value is less than the parameter given.
  333. For strings, it checks that the string length is less than that number of
  334. characters. For slices, arrays, and maps it validates the number of items.
  335. Example #1
  336. Usage: lt=10
  337. Example #2 (time.Time)
  338. For time.Time ensures the time value is less than time.Now.UTC().
  339. Usage: lt
  340. Example #3 (time.Duration)
  341. For time.Duration, lt will ensure that the value is less than the duration given
  342. in the parameter.
  343. Usage: lt=1h30m
  344. Less Than or Equal
  345. Same as 'max' above. Kept both to make terminology with 'len' easier.
  346. Example #1
  347. Usage: lte=10
  348. Example #2 (time.Time)
  349. For time.Time ensures the time value is less than or equal to time.Now.UTC().
  350. Usage: lte
  351. Example #3 (time.Duration)
  352. For time.Duration, lte will ensure that the value is less than or equal to the
  353. duration given in the parameter.
  354. Usage: lte=1h30m
  355. Field Equals Another Field
  356. This will validate the field value against another fields value either within
  357. a struct or passed in field.
  358. Example #1:
  359. // Validation on Password field using:
  360. Usage: eqfield=ConfirmPassword
  361. Example #2:
  362. // Validating by field:
  363. validate.VarWithValue(password, confirmpassword, "eqfield")
  364. Field Equals Another Field (relative)
  365. This does the same as eqfield except that it validates the field provided relative
  366. to the top level struct.
  367. Usage: eqcsfield=InnerStructField.Field)
  368. Field Does Not Equal Another Field
  369. This will validate the field value against another fields value either within
  370. a struct or passed in field.
  371. Examples:
  372. // Confirm two colors are not the same:
  373. //
  374. // Validation on Color field:
  375. Usage: nefield=Color2
  376. // Validating by field:
  377. validate.VarWithValue(color1, color2, "nefield")
  378. Field Does Not Equal Another Field (relative)
  379. This does the same as nefield except that it validates the field provided
  380. relative to the top level struct.
  381. Usage: necsfield=InnerStructField.Field
  382. Field Greater Than Another Field
  383. Only valid for Numbers, time.Duration and time.Time types, this will validate
  384. the field value against another fields value either within a struct or passed in
  385. field. usage examples are for validation of a Start and End date:
  386. Example #1:
  387. // Validation on End field using:
  388. validate.Struct Usage(gtfield=Start)
  389. Example #2:
  390. // Validating by field:
  391. validate.VarWithValue(start, end, "gtfield")
  392. Field Greater Than Another Relative Field
  393. This does the same as gtfield except that it validates the field provided
  394. relative to the top level struct.
  395. Usage: gtcsfield=InnerStructField.Field
  396. Field Greater Than or Equal To Another Field
  397. Only valid for Numbers, time.Duration and time.Time types, this will validate
  398. the field value against another fields value either within a struct or passed in
  399. field. usage examples are for validation of a Start and End date:
  400. Example #1:
  401. // Validation on End field using:
  402. validate.Struct Usage(gtefield=Start)
  403. Example #2:
  404. // Validating by field:
  405. validate.VarWithValue(start, end, "gtefield")
  406. Field Greater Than or Equal To Another Relative Field
  407. This does the same as gtefield except that it validates the field provided relative
  408. to the top level struct.
  409. Usage: gtecsfield=InnerStructField.Field
  410. Less Than Another Field
  411. Only valid for Numbers, time.Duration and time.Time types, this will validate
  412. the field value against another fields value either within a struct or passed in
  413. field. usage examples are for validation of a Start and End date:
  414. Example #1:
  415. // Validation on End field using:
  416. validate.Struct Usage(ltfield=Start)
  417. Example #2:
  418. // Validating by field:
  419. validate.VarWithValue(start, end, "ltfield")
  420. Less Than Another Relative Field
  421. This does the same as ltfield except that it validates the field provided relative
  422. to the top level struct.
  423. Usage: ltcsfield=InnerStructField.Field
  424. Less Than or Equal To Another Field
  425. Only valid for Numbers, time.Duration and time.Time types, this will validate
  426. the field value against another fields value either within a struct or passed in
  427. field. usage examples are for validation of a Start and End date:
  428. Example #1:
  429. // Validation on End field using:
  430. validate.Struct Usage(ltefield=Start)
  431. Example #2:
  432. // Validating by field:
  433. validate.VarWithValue(start, end, "ltefield")
  434. Less Than or Equal To Another Relative Field
  435. This does the same as ltefield except that it validates the field provided relative
  436. to the top level struct.
  437. Usage: ltecsfield=InnerStructField.Field
  438. Field Contains Another Field
  439. This does the same as contains except for struct fields. It should only be used
  440. with string types. See the behavior of reflect.Value.String() for behavior on
  441. other types.
  442. Usage: containsfield=InnerStructField.Field
  443. Field Excludes Another Field
  444. This does the same as excludes except for struct fields. It should only be used
  445. with string types. See the behavior of reflect.Value.String() for behavior on
  446. other types.
  447. Usage: excludesfield=InnerStructField.Field
  448. Unique
  449. For arrays & slices, unique will ensure that there are no duplicates.
  450. For maps, unique will ensure that there are no duplicate values.
  451. For slices of struct, unique will ensure that there are no duplicate values
  452. in a field of the struct specified via a parameter.
  453. // For arrays, slices, and maps:
  454. Usage: unique
  455. // For slices of struct:
  456. Usage: unique=field
  457. Alpha Only
  458. This validates that a string value contains ASCII alpha characters only
  459. Usage: alpha
  460. Alphanumeric
  461. This validates that a string value contains ASCII alphanumeric characters only
  462. Usage: alphanum
  463. Alpha Unicode
  464. This validates that a string value contains unicode alpha characters only
  465. Usage: alphaunicode
  466. Alphanumeric Unicode
  467. This validates that a string value contains unicode alphanumeric characters only
  468. Usage: alphanumunicode
  469. Boolean
  470. This validates that a string value can successfully be parsed into a boolean with strconv.ParseBool
  471. Usage: boolean
  472. Number
  473. This validates that a string value contains number values only.
  474. For integers or float it returns true.
  475. Usage: number
  476. Numeric
  477. This validates that a string value contains a basic numeric value.
  478. basic excludes exponents etc...
  479. for integers or float it returns true.
  480. Usage: numeric
  481. Hexadecimal String
  482. This validates that a string value contains a valid hexadecimal.
  483. Usage: hexadecimal
  484. Hexcolor String
  485. This validates that a string value contains a valid hex color including
  486. hashtag (#)
  487. Usage: hexcolor
  488. Lowercase String
  489. This validates that a string value contains only lowercase characters. An empty string is not a valid lowercase string.
  490. Usage: lowercase
  491. Uppercase String
  492. This validates that a string value contains only uppercase characters. An empty string is not a valid uppercase string.
  493. Usage: uppercase
  494. RGB String
  495. This validates that a string value contains a valid rgb color
  496. Usage: rgb
  497. RGBA String
  498. This validates that a string value contains a valid rgba color
  499. Usage: rgba
  500. HSL String
  501. This validates that a string value contains a valid hsl color
  502. Usage: hsl
  503. HSLA String
  504. This validates that a string value contains a valid hsla color
  505. Usage: hsla
  506. E.164 Phone Number String
  507. This validates that a string value contains a valid E.164 Phone number
  508. https://en.wikipedia.org/wiki/E.164 (ex. +1123456789)
  509. Usage: e164
  510. E-mail String
  511. This validates that a string value contains a valid email
  512. This may not conform to all possibilities of any rfc standard, but neither
  513. does any email provider accept all possibilities.
  514. Usage: email
  515. JSON String
  516. This validates that a string value is valid JSON
  517. Usage: json
  518. JWT String
  519. This validates that a string value is a valid JWT
  520. Usage: jwt
  521. File path
  522. This validates that a string value contains a valid file path and that
  523. the file exists on the machine.
  524. This is done using os.Stat, which is a platform independent function.
  525. Usage: file
  526. URL String
  527. This validates that a string value contains a valid url
  528. This will accept any url the golang request uri accepts but must contain
  529. a schema for example http:// or rtmp://
  530. Usage: url
  531. URI String
  532. This validates that a string value contains a valid uri
  533. This will accept any uri the golang request uri accepts
  534. Usage: uri
  535. Urn RFC 2141 String
  536. This validataes that a string value contains a valid URN
  537. according to the RFC 2141 spec.
  538. Usage: urn_rfc2141
  539. Base64 String
  540. This validates that a string value contains a valid base64 value.
  541. Although an empty string is valid base64 this will report an empty string
  542. as an error, if you wish to accept an empty string as valid you can use
  543. this with the omitempty tag.
  544. Usage: base64
  545. Base64URL String
  546. This validates that a string value contains a valid base64 URL safe value
  547. according the the RFC4648 spec.
  548. Although an empty string is a valid base64 URL safe value, this will report
  549. an empty string as an error, if you wish to accept an empty string as valid
  550. you can use this with the omitempty tag.
  551. Usage: base64url
  552. Bitcoin Address
  553. This validates that a string value contains a valid bitcoin address.
  554. The format of the string is checked to ensure it matches one of the three formats
  555. P2PKH, P2SH and performs checksum validation.
  556. Usage: btc_addr
  557. Bitcoin Bech32 Address (segwit)
  558. This validates that a string value contains a valid bitcoin Bech32 address as defined
  559. by bip-0173 (https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki)
  560. Special thanks to Pieter Wuille for providng reference implementations.
  561. Usage: btc_addr_bech32
  562. Ethereum Address
  563. This validates that a string value contains a valid ethereum address.
  564. The format of the string is checked to ensure it matches the standard Ethereum address format.
  565. Usage: eth_addr
  566. Contains
  567. This validates that a string value contains the substring value.
  568. Usage: contains=@
  569. Contains Any
  570. This validates that a string value contains any Unicode code points
  571. in the substring value.
  572. Usage: containsany=!@#?
  573. Contains Rune
  574. This validates that a string value contains the supplied rune value.
  575. Usage: containsrune=@
  576. Excludes
  577. This validates that a string value does not contain the substring value.
  578. Usage: excludes=@
  579. Excludes All
  580. This validates that a string value does not contain any Unicode code
  581. points in the substring value.
  582. Usage: excludesall=!@#?
  583. Excludes Rune
  584. This validates that a string value does not contain the supplied rune value.
  585. Usage: excludesrune=@
  586. Starts With
  587. This validates that a string value starts with the supplied string value
  588. Usage: startswith=hello
  589. Ends With
  590. This validates that a string value ends with the supplied string value
  591. Usage: endswith=goodbye
  592. Does Not Start With
  593. This validates that a string value does not start with the supplied string value
  594. Usage: startsnotwith=hello
  595. Does Not End With
  596. This validates that a string value does not end with the supplied string value
  597. Usage: endsnotwith=goodbye
  598. International Standard Book Number
  599. This validates that a string value contains a valid isbn10 or isbn13 value.
  600. Usage: isbn
  601. International Standard Book Number 10
  602. This validates that a string value contains a valid isbn10 value.
  603. Usage: isbn10
  604. International Standard Book Number 13
  605. This validates that a string value contains a valid isbn13 value.
  606. Usage: isbn13
  607. Universally Unique Identifier UUID
  608. This validates that a string value contains a valid UUID. Uppercase UUID values will not pass - use `uuid_rfc4122` instead.
  609. Usage: uuid
  610. Universally Unique Identifier UUID v3
  611. This validates that a string value contains a valid version 3 UUID. Uppercase UUID values will not pass - use `uuid3_rfc4122` instead.
  612. Usage: uuid3
  613. Universally Unique Identifier UUID v4
  614. This validates that a string value contains a valid version 4 UUID. Uppercase UUID values will not pass - use `uuid4_rfc4122` instead.
  615. Usage: uuid4
  616. Universally Unique Identifier UUID v5
  617. This validates that a string value contains a valid version 5 UUID. Uppercase UUID values will not pass - use `uuid5_rfc4122` instead.
  618. Usage: uuid5
  619. ASCII
  620. This validates that a string value contains only ASCII characters.
  621. NOTE: if the string is blank, this validates as true.
  622. Usage: ascii
  623. Printable ASCII
  624. This validates that a string value contains only printable ASCII characters.
  625. NOTE: if the string is blank, this validates as true.
  626. Usage: printascii
  627. Multi-Byte Characters
  628. This validates that a string value contains one or more multibyte characters.
  629. NOTE: if the string is blank, this validates as true.
  630. Usage: multibyte
  631. Data URL
  632. This validates that a string value contains a valid DataURI.
  633. NOTE: this will also validate that the data portion is valid base64
  634. Usage: datauri
  635. Latitude
  636. This validates that a string value contains a valid latitude.
  637. Usage: latitude
  638. Longitude
  639. This validates that a string value contains a valid longitude.
  640. Usage: longitude
  641. Social Security Number SSN
  642. This validates that a string value contains a valid U.S. Social Security Number.
  643. Usage: ssn
  644. Internet Protocol Address IP
  645. This validates that a string value contains a valid IP Address.
  646. Usage: ip
  647. Internet Protocol Address IPv4
  648. This validates that a string value contains a valid v4 IP Address.
  649. Usage: ipv4
  650. Internet Protocol Address IPv6
  651. This validates that a string value contains a valid v6 IP Address.
  652. Usage: ipv6
  653. Classless Inter-Domain Routing CIDR
  654. This validates that a string value contains a valid CIDR Address.
  655. Usage: cidr
  656. Classless Inter-Domain Routing CIDRv4
  657. This validates that a string value contains a valid v4 CIDR Address.
  658. Usage: cidrv4
  659. Classless Inter-Domain Routing CIDRv6
  660. This validates that a string value contains a valid v6 CIDR Address.
  661. Usage: cidrv6
  662. Transmission Control Protocol Address TCP
  663. This validates that a string value contains a valid resolvable TCP Address.
  664. Usage: tcp_addr
  665. Transmission Control Protocol Address TCPv4
  666. This validates that a string value contains a valid resolvable v4 TCP Address.
  667. Usage: tcp4_addr
  668. Transmission Control Protocol Address TCPv6
  669. This validates that a string value contains a valid resolvable v6 TCP Address.
  670. Usage: tcp6_addr
  671. User Datagram Protocol Address UDP
  672. This validates that a string value contains a valid resolvable UDP Address.
  673. Usage: udp_addr
  674. User Datagram Protocol Address UDPv4
  675. This validates that a string value contains a valid resolvable v4 UDP Address.
  676. Usage: udp4_addr
  677. User Datagram Protocol Address UDPv6
  678. This validates that a string value contains a valid resolvable v6 UDP Address.
  679. Usage: udp6_addr
  680. Internet Protocol Address IP
  681. This validates that a string value contains a valid resolvable IP Address.
  682. Usage: ip_addr
  683. Internet Protocol Address IPv4
  684. This validates that a string value contains a valid resolvable v4 IP Address.
  685. Usage: ip4_addr
  686. Internet Protocol Address IPv6
  687. This validates that a string value contains a valid resolvable v6 IP Address.
  688. Usage: ip6_addr
  689. Unix domain socket end point Address
  690. This validates that a string value contains a valid Unix Address.
  691. Usage: unix_addr
  692. Media Access Control Address MAC
  693. This validates that a string value contains a valid MAC Address.
  694. Usage: mac
  695. Note: See Go's ParseMAC for accepted formats and types:
  696. http://golang.org/src/net/mac.go?s=866:918#L29
  697. Hostname RFC 952
  698. This validates that a string value is a valid Hostname according to RFC 952 https://tools.ietf.org/html/rfc952
  699. Usage: hostname
  700. Hostname RFC 1123
  701. This validates that a string value is a valid Hostname according to RFC 1123 https://tools.ietf.org/html/rfc1123
  702. Usage: hostname_rfc1123 or if you want to continue to use 'hostname' in your tags, create an alias.
  703. Full Qualified Domain Name (FQDN)
  704. This validates that a string value contains a valid FQDN.
  705. Usage: fqdn
  706. HTML Tags
  707. This validates that a string value appears to be an HTML element tag
  708. including those described at https://developer.mozilla.org/en-US/docs/Web/HTML/Element
  709. Usage: html
  710. HTML Encoded
  711. This validates that a string value is a proper character reference in decimal
  712. or hexadecimal format
  713. Usage: html_encoded
  714. URL Encoded
  715. This validates that a string value is percent-encoded (URL encoded) according
  716. to https://tools.ietf.org/html/rfc3986#section-2.1
  717. Usage: url_encoded
  718. Directory
  719. This validates that a string value contains a valid directory and that
  720. it exists on the machine.
  721. This is done using os.Stat, which is a platform independent function.
  722. Usage: dir
  723. HostPort
  724. This validates that a string value contains a valid DNS hostname and port that
  725. can be used to valiate fields typically passed to sockets and connections.
  726. Usage: hostname_port
  727. Datetime
  728. This validates that a string value is a valid datetime based on the supplied datetime format.
  729. Supplied format must match the official Go time format layout as documented in https://golang.org/pkg/time/
  730. Usage: datetime=2006-01-02
  731. Iso3166-1 alpha-2
  732. This validates that a string value is a valid country code based on iso3166-1 alpha-2 standard.
  733. see: https://www.iso.org/iso-3166-country-codes.html
  734. Usage: iso3166_1_alpha2
  735. Iso3166-1 alpha-3
  736. This validates that a string value is a valid country code based on iso3166-1 alpha-3 standard.
  737. see: https://www.iso.org/iso-3166-country-codes.html
  738. Usage: iso3166_1_alpha3
  739. Iso3166-1 alpha-numeric
  740. This validates that a string value is a valid country code based on iso3166-1 alpha-numeric standard.
  741. see: https://www.iso.org/iso-3166-country-codes.html
  742. Usage: iso3166_1_alpha3
  743. BCP 47 Language Tag
  744. This validates that a string value is a valid BCP 47 language tag, as parsed by language.Parse.
  745. More information on https://pkg.go.dev/golang.org/x/text/language
  746. Usage: bcp47_language_tag
  747. BIC (SWIFT code)
  748. This validates that a string value is a valid Business Identifier Code (SWIFT code), defined in ISO 9362.
  749. More information on https://www.iso.org/standard/60390.html
  750. Usage: bic
  751. TimeZone
  752. This validates that a string value is a valid time zone based on the time zone database present on the system.
  753. Although empty value and Local value are allowed by time.LoadLocation golang function, they are not allowed by this validator.
  754. More information on https://golang.org/pkg/time/#LoadLocation
  755. Usage: timezone
  756. Alias Validators and Tags
  757. NOTE: When returning an error, the tag returned in "FieldError" will be
  758. the alias tag unless the dive tag is part of the alias. Everything after the
  759. dive tag is not reported as the alias tag. Also, the "ActualTag" in the before
  760. case will be the actual tag within the alias that failed.
  761. Here is a list of the current built in alias tags:
  762. "iscolor"
  763. alias is "hexcolor|rgb|rgba|hsl|hsla" (Usage: iscolor)
  764. "country_code"
  765. alias is "iso3166_1_alpha2|iso3166_1_alpha3|iso3166_1_alpha_numeric" (Usage: country_code)
  766. Validator notes:
  767. regex
  768. a regex validator won't be added because commas and = signs can be part
  769. of a regex which conflict with the validation definitions. Although
  770. workarounds can be made, they take away from using pure regex's.
  771. Furthermore it's quick and dirty but the regex's become harder to
  772. maintain and are not reusable, so it's as much a programming philosophy
  773. as anything.
  774. In place of this new validator functions should be created; a regex can
  775. be used within the validator function and even be precompiled for better
  776. efficiency within regexes.go.
  777. And the best reason, you can submit a pull request and we can keep on
  778. adding to the validation library of this package!
  779. Non standard validators
  780. A collection of validation rules that are frequently needed but are more
  781. complex than the ones found in the baked in validators.
  782. A non standard validator must be registered manually like you would
  783. with your own custom validation functions.
  784. Example of registration and use:
  785. type Test struct {
  786. TestField string `validate:"yourtag"`
  787. }
  788. t := &Test{
  789. TestField: "Test"
  790. }
  791. validate := validator.New()
  792. validate.RegisterValidation("yourtag", validators.NotBlank)
  793. Here is a list of the current non standard validators:
  794. NotBlank
  795. This validates that the value is not blank or with length zero.
  796. For strings ensures they do not contain only spaces. For channels, maps, slices and arrays
  797. ensures they don't have zero length. For others, a non empty value is required.
  798. Usage: notblank
  799. Panics
  800. This package panics when bad input is provided, this is by design, bad code like
  801. that should not make it to production.
  802. type Test struct {
  803. TestField string `validate:"nonexistantfunction=1"`
  804. }
  805. t := &Test{
  806. TestField: "Test"
  807. }
  808. validate.Struct(t) // this will panic
  809. */
  810. package validator