doc.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891
  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/v9/_examples
  7. Validation Functions Return Type error
  8. Doing things this way is actually the way the standard library does, see the
  9. file.Open method here:
  10. https://golang.org/pkg/os/#Open.
  11. The authors return type "error" to avoid the issue discussed in the following,
  12. where err is always != nil:
  13. http://stackoverflow.com/a/29138676/3158232
  14. https://github.com/go-playground/validator/issues/134
  15. Validator only InvalidValidationError for bad validation input, nil or
  16. ValidationErrors as type error; so, in your code all you need to do is check
  17. if the error returned is not nil, and if it's not check if error is
  18. InvalidValidationError ( if necessary, most of the time it isn't ) type cast
  19. it to type ValidationErrors like so err.(validator.ValidationErrors).
  20. Custom Validation Functions
  21. Custom Validation functions can be added. Example:
  22. // Structure
  23. func customFunc(fl FieldLevel) bool {
  24. if fl.Field().String() == "invalid" {
  25. return false
  26. }
  27. return true
  28. }
  29. validate.RegisterValidation("custom tag name", customFunc)
  30. // NOTES: using the same tag name as an existing function
  31. // will overwrite the existing one
  32. Cross-Field Validation
  33. Cross-Field Validation can be done via the following tags:
  34. - eqfield
  35. - nefield
  36. - gtfield
  37. - gtefield
  38. - ltfield
  39. - ltefield
  40. - eqcsfield
  41. - necsfield
  42. - gtcsfield
  43. - gtecsfield
  44. - ltcsfield
  45. - ltecsfield
  46. If, however, some custom cross-field validation is required, it can be done
  47. using a custom validation.
  48. Why not just have cross-fields validation tags (i.e. only eqcsfield and not
  49. eqfield)?
  50. The reason is efficiency. If you want to check a field within the same struct
  51. "eqfield" only has to find the field on the same struct (1 level). But, if we
  52. used "eqcsfield" it could be multiple levels down. Example:
  53. type Inner struct {
  54. StartDate time.Time
  55. }
  56. type Outer struct {
  57. InnerStructField *Inner
  58. CreatedAt time.Time `validate:"ltecsfield=InnerStructField.StartDate"`
  59. }
  60. now := time.Now()
  61. inner := &Inner{
  62. StartDate: now,
  63. }
  64. outer := &Outer{
  65. InnerStructField: inner,
  66. CreatedAt: now,
  67. }
  68. errs := validate.Struct(outer)
  69. // NOTE: when calling validate.Struct(val) topStruct will be the top level struct passed
  70. // into the function
  71. // when calling validate.FieldWithValue(val, field, tag) val will be
  72. // whatever you pass, struct, field...
  73. // when calling validate.Field(field, tag) val will be nil
  74. Multiple Validators
  75. Multiple validators on a field will process in the order defined. Example:
  76. type Test struct {
  77. Field `validate:"max=10,min=1"`
  78. }
  79. // max will be checked then min
  80. Bad Validator definitions are not handled by the library. Example:
  81. type Test struct {
  82. Field `validate:"min=10,max=0"`
  83. }
  84. // this definition of min max will never succeed
  85. Using Validator Tags
  86. Baked In Cross-Field validation only compares fields on the same struct.
  87. If Cross-Field + Cross-Struct validation is needed you should implement your
  88. own custom validator.
  89. Comma (",") is the default separator of validation tags. If you wish to
  90. have a comma included within the parameter (i.e. excludesall=,) you will need to
  91. use the UTF-8 hex representation 0x2C, which is replaced in the code as a comma,
  92. so the above will become excludesall=0x2C.
  93. type Test struct {
  94. Field `validate:"excludesall=,"` // BAD! Do not include a comma.
  95. Field `validate:"excludesall=0x2C"` // GOOD! Use the UTF-8 hex representation.
  96. }
  97. Pipe ("|") is the default separator of validation tags. If you wish to
  98. have a pipe included within the parameter i.e. excludesall=| you will need to
  99. use the UTF-8 hex representation 0x7C, which is replaced in the code as a pipe,
  100. so the above will become excludesall=0x7C
  101. type Test struct {
  102. Field `validate:"excludesall=|"` // BAD! Do not include a a pipe!
  103. Field `validate:"excludesall=0x7C"` // GOOD! Use the UTF-8 hex representation.
  104. }
  105. Baked In Validators and Tags
  106. Here is a list of the current built in validators:
  107. Skip Field
  108. Tells the validation to skip this struct field; this is particularly
  109. handy in ignoring embedded structs from being validated. (Usage: -)
  110. Usage: -
  111. Or Operator
  112. This is the 'or' operator allowing multiple validators to be used and
  113. accepted. (Usage: rbg|rgba) <-- this would allow either rgb or rgba
  114. colors to be accepted. This can also be combined with 'and' for example
  115. ( Usage: omitempty,rgb|rgba)
  116. Usage: |
  117. StructOnly
  118. When a field that is a nested struct is encountered, and contains this flag
  119. any validation on the nested struct will be run, but none of the nested
  120. struct fields will be validated. This is usefull if inside of you program
  121. you know the struct will be valid, but need to verify it has been assigned.
  122. NOTE: only "required" and "omitempty" can be used on a struct itself.
  123. Usage: structonly
  124. NoStructLevel
  125. Same as structonly tag except that any struct level validations will not run.
  126. Usage: nostructlevel
  127. Omit Empty
  128. Allows conditional validation, for example if a field is not set with
  129. a value (Determined by the "required" validator) then other validation
  130. such as min or max won't run, but if a value is set validation will run.
  131. Usage: omitempty
  132. Dive
  133. This tells the validator to dive into a slice, array or map and validate that
  134. level of the slice, array or map with the validation tags that follow.
  135. Multidimensional nesting is also supported, each level you wish to dive will
  136. require another dive tag. dive has some sub-tags, 'keys' & 'endkeys', please see
  137. the Keys & EndKeys section just below.
  138. Usage: dive
  139. Example #1
  140. [][]string with validation tag "gt=0,dive,len=1,dive,required"
  141. // gt=0 will be applied to []
  142. // len=1 will be applied to []string
  143. // required will be applied to string
  144. Example #2
  145. [][]string with validation tag "gt=0,dive,dive,required"
  146. // gt=0 will be applied to []
  147. // []string will be spared validation
  148. // required will be applied to string
  149. Keys & EndKeys
  150. These are to be used together directly after the dive tag and tells the validator
  151. that anything between 'keys' and 'endkeys' applies to the keys of a map and not the
  152. values; think of it like the 'dive' tag, but for map keys instead of values.
  153. Multidimensional nesting is also supported, each level you wish to validate will
  154. require another 'keys' and 'endkeys' tag. These tags are only valid for maps.
  155. Usage: dive,keys,othertagvalidation(s),endkeys,valuevalidationtags
  156. Example #1
  157. map[string]string with validation tag "gt=0,dive,keys,eg=1|eq=2,endkeys,required"
  158. // gt=0 will be applied to the map itself
  159. // eg=1|eq=2 will be applied to the map keys
  160. // required will be applied to map values
  161. Example #2
  162. map[[2]string]string with validation tag "gt=0,dive,keys,dive,eq=1|eq=2,endkeys,required"
  163. // gt=0 will be applied to the map itself
  164. // eg=1|eq=2 will be applied to each array element in the the map keys
  165. // required will be applied to map values
  166. Required
  167. This validates that the value is not the data types default zero value.
  168. For numbers ensures value is not zero. For strings ensures value is
  169. not "". For slices, maps, pointers, interfaces, channels and functions
  170. ensures the value is not nil.
  171. Usage: required
  172. Is Default
  173. This validates that the value is the default value and is almost the
  174. opposite of required.
  175. Usage: isdefault
  176. Length
  177. For numbers, length will ensure that the value is
  178. equal to the parameter given. For strings, it checks that
  179. the string length is exactly that number of characters. For slices,
  180. arrays, and maps, validates the number of items.
  181. Usage: len=10
  182. Maximum
  183. For numbers, max will ensure that the value is
  184. less than or equal to the parameter given. For strings, it checks
  185. that the string length is at most that number of characters. For
  186. slices, arrays, and maps, validates the number of items.
  187. Usage: max=10
  188. Minimum
  189. For numbers, min will ensure that the value is
  190. greater or equal to the parameter given. For strings, it checks that
  191. the string length is at least that number of characters. For slices,
  192. arrays, and maps, validates the number of items.
  193. Usage: min=10
  194. Equals
  195. For strings & numbers, eq will ensure that the value is
  196. equal to the parameter given. For slices, arrays, and maps,
  197. validates the number of items.
  198. Usage: eq=10
  199. Not Equal
  200. For strings & numbers, ne will ensure that the value is not
  201. equal to the parameter given. For slices, arrays, and maps,
  202. validates the number of items.
  203. Usage: ne=10
  204. Greater Than
  205. For numbers, this will ensure that the value is greater than the
  206. parameter given. For strings, it checks that the string length
  207. is greater than that number of characters. For slices, arrays
  208. and maps it validates the number of items.
  209. Example #1
  210. Usage: gt=10
  211. Example #2 (time.Time)
  212. For time.Time ensures the time value is greater than time.Now.UTC().
  213. Usage: gt
  214. Greater Than or Equal
  215. Same as 'min' above. Kept both to make terminology with 'len' easier.
  216. Example #1
  217. Usage: gte=10
  218. Example #2 (time.Time)
  219. For time.Time ensures the time value is greater than or equal to time.Now.UTC().
  220. Usage: gte
  221. Less Than
  222. For numbers, this will ensure that the value is less than the parameter given.
  223. For strings, it checks that the string length is less than that number of
  224. characters. For slices, arrays, and maps it validates the number of items.
  225. Example #1
  226. Usage: lt=10
  227. Example #2 (time.Time)
  228. For time.Time ensures the time value is less than time.Now.UTC().
  229. Usage: lt
  230. Less Than or Equal
  231. Same as 'max' above. Kept both to make terminology with 'len' easier.
  232. Example #1
  233. Usage: lte=10
  234. Example #2 (time.Time)
  235. For time.Time ensures the time value is less than or equal to time.Now.UTC().
  236. Usage: lte
  237. Field Equals Another Field
  238. This will validate the field value against another fields value either within
  239. a struct or passed in field.
  240. Example #1:
  241. // Validation on Password field using:
  242. Usage: eqfield=ConfirmPassword
  243. Example #2:
  244. // Validating by field:
  245. validate.FieldWithValue(password, confirmpassword, "eqfield")
  246. Field Equals Another Field (relative)
  247. This does the same as eqfield except that it validates the field provided relative
  248. to the top level struct.
  249. Usage: eqcsfield=InnerStructField.Field)
  250. Field Does Not Equal Another Field
  251. This will validate the field value against another fields value either within
  252. a struct or passed in field.
  253. Examples:
  254. // Confirm two colors are not the same:
  255. //
  256. // Validation on Color field:
  257. Usage: nefield=Color2
  258. // Validating by field:
  259. validate.FieldWithValue(color1, color2, "nefield")
  260. Field Does Not Equal Another Field (relative)
  261. This does the same as nefield except that it validates the field provided
  262. relative to the top level struct.
  263. Usage: necsfield=InnerStructField.Field
  264. Field Greater Than Another Field
  265. Only valid for Numbers and time.Time types, this will validate the field value
  266. against another fields value either within a struct or passed in field.
  267. usage examples are for validation of a Start and End date:
  268. Example #1:
  269. // Validation on End field using:
  270. validate.Struct Usage(gtfield=Start)
  271. Example #2:
  272. // Validating by field:
  273. validate.FieldWithValue(start, end, "gtfield")
  274. Field Greater Than Another Relative Field
  275. This does the same as gtfield except that it validates the field provided
  276. relative to the top level struct.
  277. Usage: gtcsfield=InnerStructField.Field
  278. Field Greater Than or Equal To Another Field
  279. Only valid for Numbers and time.Time types, this will validate the field value
  280. against another fields value either within a struct or passed in field.
  281. usage examples are for validation of a Start and End date:
  282. Example #1:
  283. // Validation on End field using:
  284. validate.Struct Usage(gtefield=Start)
  285. Example #2:
  286. // Validating by field:
  287. validate.FieldWithValue(start, end, "gtefield")
  288. Field Greater Than or Equal To Another Relative Field
  289. This does the same as gtefield except that it validates the field provided relative
  290. to the top level struct.
  291. Usage: gtecsfield=InnerStructField.Field
  292. Less Than Another Field
  293. Only valid for Numbers and time.Time types, this will validate the field value
  294. against another fields value either within a struct or passed in field.
  295. usage examples are for validation of a Start and End date:
  296. Example #1:
  297. // Validation on End field using:
  298. validate.Struct Usage(ltfield=Start)
  299. Example #2:
  300. // Validating by field:
  301. validate.FieldWithValue(start, end, "ltfield")
  302. Less Than Another Relative Field
  303. This does the same as ltfield except that it validates the field provided relative
  304. to the top level struct.
  305. Usage: ltcsfield=InnerStructField.Field
  306. Less Than or Equal To Another Field
  307. Only valid for Numbers and time.Time types, this will validate the field value
  308. against another fields value either within a struct or passed in field.
  309. usage examples are for validation of a Start and End date:
  310. Example #1:
  311. // Validation on End field using:
  312. validate.Struct Usage(ltefield=Start)
  313. Example #2:
  314. // Validating by field:
  315. validate.FieldWithValue(start, end, "ltefield")
  316. Less Than or Equal To Another Relative Field
  317. This does the same as ltefield except that it validates the field provided relative
  318. to the top level struct.
  319. Usage: ltecsfield=InnerStructField.Field
  320. Unique
  321. For arrays & slices, unique will ensure that there are no duplicates.
  322. Usage: unique
  323. Alpha Only
  324. This validates that a string value contains ASCII alpha characters only
  325. Usage: alpha
  326. Alphanumeric
  327. This validates that a string value contains ASCII alphanumeric characters only
  328. Usage: alphanum
  329. Alpha Unicode
  330. This validates that a string value contains unicode alpha characters only
  331. Usage: alphaunicode
  332. Alphanumeric Unicode
  333. This validates that a string value contains unicode alphanumeric characters only
  334. Usage: alphanumunicode
  335. Numeric
  336. This validates that a string value contains a basic numeric value.
  337. basic excludes exponents etc...
  338. Usage: numeric
  339. Hexadecimal String
  340. This validates that a string value contains a valid hexadecimal.
  341. Usage: hexadecimal
  342. Hexcolor String
  343. This validates that a string value contains a valid hex color including
  344. hashtag (#)
  345. Usage: hexcolor
  346. RGB String
  347. This validates that a string value contains a valid rgb color
  348. Usage: rgb
  349. RGBA String
  350. This validates that a string value contains a valid rgba color
  351. Usage: rgba
  352. HSL String
  353. This validates that a string value contains a valid hsl color
  354. Usage: hsl
  355. HSLA String
  356. This validates that a string value contains a valid hsla color
  357. Usage: hsla
  358. E-mail String
  359. This validates that a string value contains a valid email
  360. This may not conform to all possibilities of any rfc standard, but neither
  361. does any email provider accept all posibilities.
  362. Usage: email
  363. URL String
  364. This validates that a string value contains a valid url
  365. This will accept any url the golang request uri accepts but must contain
  366. a schema for example http:// or rtmp://
  367. Usage: url
  368. URI String
  369. This validates that a string value contains a valid uri
  370. This will accept any uri the golang request uri accepts
  371. Usage: uri
  372. Base64 String
  373. This validates that a string value contains a valid base64 value.
  374. Although an empty string is valid base64 this will report an empty string
  375. as an error, if you wish to accept an empty string as valid you can use
  376. this with the omitempty tag.
  377. Usage: base64
  378. Contains
  379. This validates that a string value contains the substring value.
  380. Usage: contains=@
  381. Contains Any
  382. This validates that a string value contains any Unicode code points
  383. in the substring value.
  384. Usage: containsany=!@#?
  385. Contains Rune
  386. This validates that a string value contains the supplied rune value.
  387. Usage: containsrune=@
  388. Excludes
  389. This validates that a string value does not contain the substring value.
  390. Usage: excludes=@
  391. Excludes All
  392. This validates that a string value does not contain any Unicode code
  393. points in the substring value.
  394. Usage: excludesall=!@#?
  395. Excludes Rune
  396. This validates that a string value does not contain the supplied rune value.
  397. Usage: excludesrune=@
  398. International Standard Book Number
  399. This validates that a string value contains a valid isbn10 or isbn13 value.
  400. Usage: isbn
  401. International Standard Book Number 10
  402. This validates that a string value contains a valid isbn10 value.
  403. Usage: isbn10
  404. International Standard Book Number 13
  405. This validates that a string value contains a valid isbn13 value.
  406. Usage: isbn13
  407. Universally Unique Identifier UUID
  408. This validates that a string value contains a valid UUID.
  409. Usage: uuid
  410. Universally Unique Identifier UUID v3
  411. This validates that a string value contains a valid version 3 UUID.
  412. Usage: uuid3
  413. Universally Unique Identifier UUID v4
  414. This validates that a string value contains a valid version 4 UUID.
  415. Usage: uuid4
  416. Universally Unique Identifier UUID v5
  417. This validates that a string value contains a valid version 5 UUID.
  418. Usage: uuid5
  419. ASCII
  420. This validates that a string value contains only ASCII characters.
  421. NOTE: if the string is blank, this validates as true.
  422. Usage: ascii
  423. Printable ASCII
  424. This validates that a string value contains only printable ASCII characters.
  425. NOTE: if the string is blank, this validates as true.
  426. Usage: printascii
  427. Multi-Byte Characters
  428. This validates that a string value contains one or more multibyte characters.
  429. NOTE: if the string is blank, this validates as true.
  430. Usage: multibyte
  431. Data URL
  432. This validates that a string value contains a valid DataURI.
  433. NOTE: this will also validate that the data portion is valid base64
  434. Usage: datauri
  435. Latitude
  436. This validates that a string value contains a valid latitude.
  437. Usage: latitude
  438. Longitude
  439. This validates that a string value contains a valid longitude.
  440. Usage: longitude
  441. Social Security Number SSN
  442. This validates that a string value contains a valid U.S. Social Security Number.
  443. Usage: ssn
  444. Internet Protocol Address IP
  445. This validates that a string value contains a valid IP Adress.
  446. Usage: ip
  447. Internet Protocol Address IPv4
  448. This validates that a string value contains a valid v4 IP Adress.
  449. Usage: ipv4
  450. Internet Protocol Address IPv6
  451. This validates that a string value contains a valid v6 IP Adress.
  452. Usage: ipv6
  453. Classless Inter-Domain Routing CIDR
  454. This validates that a string value contains a valid CIDR Adress.
  455. Usage: cidr
  456. Classless Inter-Domain Routing CIDRv4
  457. This validates that a string value contains a valid v4 CIDR Adress.
  458. Usage: cidrv4
  459. Classless Inter-Domain Routing CIDRv6
  460. This validates that a string value contains a valid v6 CIDR Adress.
  461. Usage: cidrv6
  462. Transmission Control Protocol Address TCP
  463. This validates that a string value contains a valid resolvable TCP Adress.
  464. Usage: tcp_addr
  465. Transmission Control Protocol Address TCPv4
  466. This validates that a string value contains a valid resolvable v4 TCP Adress.
  467. Usage: tcp4_addr
  468. Transmission Control Protocol Address TCPv6
  469. This validates that a string value contains a valid resolvable v6 TCP Adress.
  470. Usage: tcp6_addr
  471. User Datagram Protocol Address UDP
  472. This validates that a string value contains a valid resolvable UDP Adress.
  473. Usage: udp_addr
  474. User Datagram Protocol Address UDPv4
  475. This validates that a string value contains a valid resolvable v4 UDP Adress.
  476. Usage: udp4_addr
  477. User Datagram Protocol Address UDPv6
  478. This validates that a string value contains a valid resolvable v6 UDP Adress.
  479. Usage: udp6_addr
  480. Internet Protocol Address IP
  481. This validates that a string value contains a valid resolvable IP Adress.
  482. Usage: ip_addr
  483. Internet Protocol Address IPv4
  484. This validates that a string value contains a valid resolvable v4 IP Adress.
  485. Usage: ip4_addr
  486. Internet Protocol Address IPv6
  487. This validates that a string value contains a valid resolvable v6 IP Adress.
  488. Usage: ip6_addr
  489. Unix domain socket end point Address
  490. This validates that a string value contains a valid Unix Adress.
  491. Usage: unix_addr
  492. Media Access Control Address MAC
  493. This validates that a string value contains a valid MAC Adress.
  494. Usage: mac
  495. Note: See Go's ParseMAC for accepted formats and types:
  496. http://golang.org/src/net/mac.go?s=866:918#L29
  497. Hostname
  498. This validates that a string value is a valid Hostname
  499. Usage: hostname
  500. Full Qualified Domain Name (FQDN)
  501. This validates that a string value contains a valid FQDN.
  502. Usage: fqdn
  503. Alias Validators and Tags
  504. NOTE: When returning an error, the tag returned in "FieldError" will be
  505. the alias tag unless the dive tag is part of the alias. Everything after the
  506. dive tag is not reported as the alias tag. Also, the "ActualTag" in the before
  507. case will be the actual tag within the alias that failed.
  508. Here is a list of the current built in alias tags:
  509. "iscolor"
  510. alias is "hexcolor|rgb|rgba|hsl|hsla" (Usage: iscolor)
  511. Validator notes:
  512. regex
  513. a regex validator won't be added because commas and = signs can be part
  514. of a regex which conflict with the validation definitions. Although
  515. workarounds can be made, they take away from using pure regex's.
  516. Furthermore it's quick and dirty but the regex's become harder to
  517. maintain and are not reusable, so it's as much a programming philosiphy
  518. as anything.
  519. In place of this new validator functions should be created; a regex can
  520. be used within the validator function and even be precompiled for better
  521. efficiency within regexes.go.
  522. And the best reason, you can submit a pull request and we can keep on
  523. adding to the validation library of this package!
  524. Panics
  525. This package panics when bad input is provided, this is by design, bad code like
  526. that should not make it to production.
  527. type Test struct {
  528. TestField string `validate:"nonexistantfunction=1"`
  529. }
  530. t := &Test{
  531. TestField: "Test"
  532. }
  533. validate.Struct(t) // this will panic
  534. */
  535. package validator