doc.go 38 KB

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