doc.go 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401
  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. 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.
  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.
  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 path
  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. URL String
  549. This validates that a string value contains a valid url
  550. This will accept any url the golang request uri accepts but must contain
  551. a schema for example http:// or rtmp://
  552. Usage: url
  553. URI String
  554. This validates that a string value contains a valid uri
  555. This will accept any uri the golang request uri accepts
  556. Usage: uri
  557. Urn RFC 2141 String
  558. This validataes that a string value contains a valid URN
  559. according to the RFC 2141 spec.
  560. Usage: urn_rfc2141
  561. Base64 String
  562. This validates that a string value contains a valid base64 value.
  563. Although an empty string is valid base64 this will report an empty string
  564. as an error, if you wish to accept an empty string as valid you can use
  565. this with the omitempty tag.
  566. Usage: base64
  567. Base64URL String
  568. This validates that a string value contains a valid base64 URL safe value
  569. according the the RFC4648 spec.
  570. Although an empty string is a valid base64 URL safe value, this will report
  571. an empty string as an error, if you wish to accept an empty string as valid
  572. you can use this with the omitempty tag.
  573. Usage: base64url
  574. Bitcoin Address
  575. This validates that a string value contains a valid bitcoin address.
  576. The format of the string is checked to ensure it matches one of the three formats
  577. P2PKH, P2SH and performs checksum validation.
  578. Usage: btc_addr
  579. Bitcoin Bech32 Address (segwit)
  580. This validates that a string value contains a valid bitcoin Bech32 address as defined
  581. by bip-0173 (https://github.com/bitcoin/bips/blob/master/bip-0173.mediawiki)
  582. Special thanks to Pieter Wuille for providng reference implementations.
  583. Usage: btc_addr_bech32
  584. Ethereum Address
  585. This validates that a string value contains a valid ethereum address.
  586. The format of the string is checked to ensure it matches the standard Ethereum address format.
  587. Usage: eth_addr
  588. Contains
  589. This validates that a string value contains the substring value.
  590. Usage: contains=@
  591. Contains Any
  592. This validates that a string value contains any Unicode code points
  593. in the substring value.
  594. Usage: containsany=!@#?
  595. Contains Rune
  596. This validates that a string value contains the supplied rune value.
  597. Usage: containsrune=@
  598. Excludes
  599. This validates that a string value does not contain the substring value.
  600. Usage: excludes=@
  601. Excludes All
  602. This validates that a string value does not contain any Unicode code
  603. points in the substring value.
  604. Usage: excludesall=!@#?
  605. Excludes Rune
  606. This validates that a string value does not contain the supplied rune value.
  607. Usage: excludesrune=@
  608. Starts With
  609. This validates that a string value starts with the supplied string value
  610. Usage: startswith=hello
  611. Ends With
  612. This validates that a string value ends with the supplied string value
  613. Usage: endswith=goodbye
  614. Does Not Start With
  615. This validates that a string value does not start with the supplied string value
  616. Usage: startsnotwith=hello
  617. Does Not End With
  618. This validates that a string value does not end with the supplied string value
  619. Usage: endsnotwith=goodbye
  620. International Standard Book Number
  621. This validates that a string value contains a valid isbn10 or isbn13 value.
  622. Usage: isbn
  623. International Standard Book Number 10
  624. This validates that a string value contains a valid isbn10 value.
  625. Usage: isbn10
  626. International Standard Book Number 13
  627. This validates that a string value contains a valid isbn13 value.
  628. Usage: isbn13
  629. Universally Unique Identifier UUID
  630. This validates that a string value contains a valid UUID. Uppercase UUID values will not pass - use `uuid_rfc4122` instead.
  631. Usage: uuid
  632. Universally Unique Identifier UUID v3
  633. This validates that a string value contains a valid version 3 UUID. Uppercase UUID values will not pass - use `uuid3_rfc4122` instead.
  634. Usage: uuid3
  635. Universally Unique Identifier UUID v4
  636. This validates that a string value contains a valid version 4 UUID. Uppercase UUID values will not pass - use `uuid4_rfc4122` instead.
  637. Usage: uuid4
  638. Universally Unique Identifier UUID v5
  639. This validates that a string value contains a valid version 5 UUID. Uppercase UUID values will not pass - use `uuid5_rfc4122` instead.
  640. Usage: uuid5
  641. Universally Unique Lexicographically Sortable Identifier ULID
  642. This validates that a string value contains a valid ULID value.
  643. Usage: ulid
  644. ASCII
  645. This validates that a string value contains only ASCII characters.
  646. NOTE: if the string is blank, this validates as true.
  647. Usage: ascii
  648. Printable ASCII
  649. This validates that a string value contains only printable ASCII characters.
  650. NOTE: if the string is blank, this validates as true.
  651. Usage: printascii
  652. Multi-Byte Characters
  653. This validates that a string value contains one or more multibyte characters.
  654. NOTE: if the string is blank, this validates as true.
  655. Usage: multibyte
  656. Data URL
  657. This validates that a string value contains a valid DataURI.
  658. NOTE: this will also validate that the data portion is valid base64
  659. Usage: datauri
  660. Latitude
  661. This validates that a string value contains a valid latitude.
  662. Usage: latitude
  663. Longitude
  664. This validates that a string value contains a valid longitude.
  665. Usage: longitude
  666. Social Security Number SSN
  667. This validates that a string value contains a valid U.S. Social Security Number.
  668. Usage: ssn
  669. Internet Protocol Address IP
  670. This validates that a string value contains a valid IP Address.
  671. Usage: ip
  672. Internet Protocol Address IPv4
  673. This validates that a string value contains a valid v4 IP Address.
  674. Usage: ipv4
  675. Internet Protocol Address IPv6
  676. This validates that a string value contains a valid v6 IP Address.
  677. Usage: ipv6
  678. Classless Inter-Domain Routing CIDR
  679. This validates that a string value contains a valid CIDR Address.
  680. Usage: cidr
  681. Classless Inter-Domain Routing CIDRv4
  682. This validates that a string value contains a valid v4 CIDR Address.
  683. Usage: cidrv4
  684. Classless Inter-Domain Routing CIDRv6
  685. This validates that a string value contains a valid v6 CIDR Address.
  686. Usage: cidrv6
  687. Transmission Control Protocol Address TCP
  688. This validates that a string value contains a valid resolvable TCP Address.
  689. Usage: tcp_addr
  690. Transmission Control Protocol Address TCPv4
  691. This validates that a string value contains a valid resolvable v4 TCP Address.
  692. Usage: tcp4_addr
  693. Transmission Control Protocol Address TCPv6
  694. This validates that a string value contains a valid resolvable v6 TCP Address.
  695. Usage: tcp6_addr
  696. User Datagram Protocol Address UDP
  697. This validates that a string value contains a valid resolvable UDP Address.
  698. Usage: udp_addr
  699. User Datagram Protocol Address UDPv4
  700. This validates that a string value contains a valid resolvable v4 UDP Address.
  701. Usage: udp4_addr
  702. User Datagram Protocol Address UDPv6
  703. This validates that a string value contains a valid resolvable v6 UDP Address.
  704. Usage: udp6_addr
  705. Internet Protocol Address IP
  706. This validates that a string value contains a valid resolvable IP Address.
  707. Usage: ip_addr
  708. Internet Protocol Address IPv4
  709. This validates that a string value contains a valid resolvable v4 IP Address.
  710. Usage: ip4_addr
  711. Internet Protocol Address IPv6
  712. This validates that a string value contains a valid resolvable v6 IP Address.
  713. Usage: ip6_addr
  714. Unix domain socket end point Address
  715. This validates that a string value contains a valid Unix Address.
  716. Usage: unix_addr
  717. Media Access Control Address MAC
  718. This validates that a string value contains a valid MAC Address.
  719. Usage: mac
  720. Note: See Go's ParseMAC for accepted formats and types:
  721. http://golang.org/src/net/mac.go?s=866:918#L29
  722. Hostname RFC 952
  723. This validates that a string value is a valid Hostname according to RFC 952 https://tools.ietf.org/html/rfc952
  724. Usage: hostname
  725. Hostname RFC 1123
  726. This validates that a string value is a valid Hostname according to RFC 1123 https://tools.ietf.org/html/rfc1123
  727. Usage: hostname_rfc1123 or if you want to continue to use 'hostname' in your tags, create an alias.
  728. Full Qualified Domain Name (FQDN)
  729. This validates that a string value contains a valid FQDN.
  730. Usage: fqdn
  731. HTML Tags
  732. This validates that a string value appears to be an HTML element tag
  733. including those described at https://developer.mozilla.org/en-US/docs/Web/HTML/Element
  734. Usage: html
  735. HTML Encoded
  736. This validates that a string value is a proper character reference in decimal
  737. or hexadecimal format
  738. Usage: html_encoded
  739. URL Encoded
  740. This validates that a string value is percent-encoded (URL encoded) according
  741. to https://tools.ietf.org/html/rfc3986#section-2.1
  742. Usage: url_encoded
  743. Directory
  744. This validates that a string value contains a valid directory and that
  745. it exists on the machine.
  746. This is done using os.Stat, which is a platform independent function.
  747. Usage: dir
  748. HostPort
  749. This validates that a string value contains a valid DNS hostname and port that
  750. can be used to valiate fields typically passed to sockets and connections.
  751. Usage: hostname_port
  752. Datetime
  753. This validates that a string value is a valid datetime based on the supplied datetime format.
  754. Supplied format must match the official Go time format layout as documented in https://golang.org/pkg/time/
  755. Usage: datetime=2006-01-02
  756. Iso3166-1 alpha-2
  757. This validates that a string value is a valid country code based on iso3166-1 alpha-2 standard.
  758. see: https://www.iso.org/iso-3166-country-codes.html
  759. Usage: iso3166_1_alpha2
  760. Iso3166-1 alpha-3
  761. This validates that a string value is a valid country code based on iso3166-1 alpha-3 standard.
  762. see: https://www.iso.org/iso-3166-country-codes.html
  763. Usage: iso3166_1_alpha3
  764. Iso3166-1 alpha-numeric
  765. This validates that a string value is a valid country code based on iso3166-1 alpha-numeric standard.
  766. see: https://www.iso.org/iso-3166-country-codes.html
  767. Usage: iso3166_1_alpha3
  768. BCP 47 Language Tag
  769. This validates that a string value is a valid BCP 47 language tag, as parsed by language.Parse.
  770. More information on https://pkg.go.dev/golang.org/x/text/language
  771. Usage: bcp47_language_tag
  772. BIC (SWIFT code)
  773. This validates that a string value is a valid Business Identifier Code (SWIFT code), defined in ISO 9362.
  774. More information on https://www.iso.org/standard/60390.html
  775. Usage: bic
  776. RFC 1035 label
  777. This validates that a string value is a valid dns RFC 1035 label, defined in RFC 1035.
  778. More information on https://datatracker.ietf.org/doc/html/rfc1035
  779. Usage: dns_rfc1035_label
  780. TimeZone
  781. This validates that a string value is a valid time zone based on the time zone database present on the system.
  782. Although empty value and Local value are allowed by time.LoadLocation golang function, they are not allowed by this validator.
  783. More information on https://golang.org/pkg/time/#LoadLocation
  784. Usage: timezone
  785. Semantic Version
  786. This validates that a string value is a valid semver version, defined in Semantic Versioning 2.0.0.
  787. More information on https://semver.org/
  788. Usage: semver
  789. Credit Card
  790. This validates that a string value contains a valid credit card number using Luhn algoritm.
  791. Usage: credit_card
  792. Alias Validators and Tags
  793. NOTE: When returning an error, the tag returned in "FieldError" will be
  794. the alias tag unless the dive tag is part of the alias. Everything after the
  795. dive tag is not reported as the alias tag. Also, the "ActualTag" in the before
  796. case will be the actual tag within the alias that failed.
  797. Here is a list of the current built in alias tags:
  798. "iscolor"
  799. alias is "hexcolor|rgb|rgba|hsl|hsla" (Usage: iscolor)
  800. "country_code"
  801. alias is "iso3166_1_alpha2|iso3166_1_alpha3|iso3166_1_alpha_numeric" (Usage: country_code)
  802. Validator notes:
  803. regex
  804. a regex validator won't be added because commas and = signs can be part
  805. of a regex which conflict with the validation definitions. Although
  806. workarounds can be made, they take away from using pure regex's.
  807. Furthermore it's quick and dirty but the regex's become harder to
  808. maintain and are not reusable, so it's as much a programming philosophy
  809. as anything.
  810. In place of this new validator functions should be created; a regex can
  811. be used within the validator function and even be precompiled for better
  812. efficiency within regexes.go.
  813. And the best reason, you can submit a pull request and we can keep on
  814. adding to the validation library of this package!
  815. Non standard validators
  816. A collection of validation rules that are frequently needed but are more
  817. complex than the ones found in the baked in validators.
  818. A non standard validator must be registered manually like you would
  819. with your own custom validation functions.
  820. Example of registration and use:
  821. type Test struct {
  822. TestField string `validate:"yourtag"`
  823. }
  824. t := &Test{
  825. TestField: "Test"
  826. }
  827. validate := validator.New()
  828. validate.RegisterValidation("yourtag", validators.NotBlank)
  829. Here is a list of the current non standard validators:
  830. NotBlank
  831. This validates that the value is not blank or with length zero.
  832. For strings ensures they do not contain only spaces. For channels, maps, slices and arrays
  833. ensures they don't have zero length. For others, a non empty value is required.
  834. Usage: notblank
  835. Panics
  836. This package panics when bad input is provided, this is by design, bad code like
  837. that should not make it to production.
  838. type Test struct {
  839. TestField string `validate:"nonexistantfunction=1"`
  840. }
  841. t := &Test{
  842. TestField: "Test"
  843. }
  844. validate.Struct(t) // this will panic
  845. */
  846. package validator