doc.go 33 KB

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