doc.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  1. /*
  2. Package validator implements value validations for structs and individual fields based on tags. It can also handle Cross Field validation and even Cross Field Cross Struct validation for nested structs.
  3. Built In Validator
  4. myValidator = validator.NewValidator("validate", validator.BakedInValidators)
  5. errs := myValidator.ValidateStruct(//your struct)
  6. valErr := myValidator.ValidateFieldByTag(field, "omitempty,min=1,max=10")
  7. A simple example usage:
  8. type UserDetail {
  9. Details string `validate:"-"`
  10. }
  11. type User struct {
  12. Name string `validate:"required,max=60"`
  13. PreferedName string `validate:"omitempty,max=60"`
  14. Sub UserDetail
  15. }
  16. user := &User {
  17. Name: "",
  18. }
  19. // errs will contain a hierarchical list of errors
  20. // using the StructValidationErrors struct
  21. // or nil if no errors exist
  22. errs := myValidator.ValidateStruct(user)
  23. // in this case 1 error Name is required
  24. errs.Struct will be "User"
  25. errs.StructErrors will be empty <-- fields that were structs
  26. errs.Errors will have 1 error of type FieldValidationError
  27. NOTE: Anonymous Structs - they don't have names so expect the Struct name
  28. within StructValidationErrors to be blank.
  29. Error Handling
  30. The error can be used like so
  31. fieldErr, _ := errs["Name"]
  32. fieldErr.Field // "Name"
  33. fieldErr.ErrorTag // "required"
  34. Both StructValidationErrors and FieldValidationError implement the Error interface but it's
  35. intended use is for development + debugging, not a production error message.
  36. fieldErr.Error() // Field validation for "Name" failed on the "required" tag
  37. errs.Error()
  38. // Struct: User
  39. // Field validation for "Name" failed on the "required" tag
  40. Why not a better error message? because this library intends for you to handle your own error messages
  41. Why should I handle my own errors? Many reasons, for us building an internationalized application
  42. I needed to know the field and what validation failed so that I could provide an error in the users specific language.
  43. if fieldErr.Field == "Name" {
  44. switch fieldErr.ErrorTag
  45. case "required":
  46. return "Translated string based on field + error"
  47. default:
  48. return "Translated string based on field"
  49. }
  50. The hierarchical error structure is hard to work with sometimes.. Agreed Flatten function to the rescue!
  51. Flatten will return a map of FieldValidationError's but the field name will be namespaced.
  52. // if UserDetail Details field failed validation
  53. Field will be "Sub.Details"
  54. // for Name
  55. Field will be "Name"
  56. Custom Functions
  57. Custom functions can be added
  58. //Structure
  59. func customFunc(top interface{}, current interface{}, field interface{}, param string) bool {
  60. if whatever {
  61. return false
  62. }
  63. return true
  64. }
  65. myValidator.AddFunction("custom tag name", customFunc)
  66. // NOTES: using the same tag name as an existing function
  67. // will overwrite the existing one
  68. Cross Field Validation
  69. Cross Field Validation can be implemented, for example Start & End Date range validation
  70. // NOTE: when calling myValidator.validateStruct(val) val will be the top level struct passed
  71. // into the function
  72. // when calling myValidator.ValidateFieldByTagAndValue(val, field, tag) val will be
  73. // whatever you pass, struct, field...
  74. // when calling myValidator.ValidateFieldByTag(field, tag) val will be nil
  75. //
  76. // Because of the specific requirements and field names within each persons project that
  77. // uses this library it is likely that custom functions will need to be created for your
  78. // Cross Field Validation needs, however there are some build in Generic Cross Field validations,
  79. // see Baked In Validators and Tags below
  80. func isDateRangeValid(val interface{}, field interface{}, param string) bool {
  81. myStruct := val.(myStructType)
  82. if myStruct.Start.After(field.(time.Time)) {
  83. return false
  84. }
  85. return true
  86. }
  87. Multiple Validators
  88. Multiple validators on a field will process in the order defined
  89. type Test struct {
  90. Field `validate:"max=10,min=1"`
  91. }
  92. // max will be checked then min
  93. Bad Validator definitions are not handled by the library
  94. type Test struct {
  95. Field `validate:"min=10,max=0"`
  96. }
  97. // this definition of min max will never validate
  98. Baked In Validators and Tags
  99. NOTE: Baked In Cross field validation only compares fields on the same struct,
  100. if cross field + cross struct validation is needed your own custom validator
  101. should be implemented.
  102. Here is a list of the current built in validators:
  103. -
  104. Tells the validation to skip this struct field; this is particularily
  105. handy in ignoring embedded structs from being validated. (Usage: -)
  106. |
  107. This is the 'or' operator allowing multiple validators to be used and
  108. accepted. (Usage: rbg|rgba) <-- this would allow either rgb or rgba
  109. colors to be accepted. This can also be combined with 'and' for example
  110. ( Usage: omitempty,rgb|rgba)
  111. structonly
  112. When a field that is a nest struct in encountered and contains this flag
  113. any validation on the nested struct such as "required" will be run, but
  114. none of the nested struct fields will be validated. This is usefull if
  115. inside of you program you know the struct will be valid, but need to
  116. verify it has been assigned.
  117. omitempty
  118. Allows conitional validation, for example if a field is not set with
  119. a value (Determined by the required validator) then other validation
  120. such as min or max won't run, but if a value is set validation will run.
  121. (Usage: omitempty)
  122. required
  123. This validates that the value is not the data types default value.
  124. For numbers ensures value is not zero. For strings ensures value is
  125. not "". For slices, arrays, and maps, ensures the length is not zero.
  126. (Usage: required)
  127. len
  128. For numbers, max will ensure that the value is
  129. equal to the parameter given. For strings, it checks that
  130. the string length is exactly that number of characters. For slices,
  131. arrays, and maps, validates the number of items. (Usage: len=10)
  132. max
  133. For numbers, max will ensure that the value is
  134. less than or equal to the parameter given. For strings, it checks
  135. that the string length is at most that number of characters. For
  136. slices, arrays, and maps, validates the number of items. (Usage: max=10)
  137. min
  138. For numbers, min will ensure that the value is
  139. greater or equal to the parameter given. For strings, it checks that
  140. the string length is at least that number of characters. For slices,
  141. arrays, and maps, validates the number of items. (Usage: min=10)
  142. gt
  143. For numbers, this will ensure that the value is greater than the
  144. parameter given. For strings, it checks that the string length
  145. is greater than that number of characters. For slices, arrays
  146. and maps it validates the number of items. (Usage: gt=10)
  147. For time.Time ensures the time value is greater than time.Now.UTC()
  148. (Usage: gt)
  149. gte
  150. Same as 'min' above. Kept both to make terminology with 'len' easier
  151. (Usage: gte=10)
  152. For time.Time ensures the time value is greater than or equal to time.Now.UTC()
  153. (Usage: gte)
  154. lt
  155. For numbers, this will ensure that the value is
  156. less than the parameter given. For strings, it checks
  157. that the string length is less than that number of characters.
  158. For slices, arrays, and maps it validates the number of items.
  159. (Usage: lt=10)
  160. For time.Time ensures the time value is less than time.Now.UTC()
  161. (Usage: lt)
  162. lte
  163. Same as 'max' above. Kept both to make terminology with 'len' easier
  164. (Usage: lte=10)
  165. For time.Time ensures the time value is less than or equal to time.Now.UTC()
  166. (Usage: lte)
  167. gtfield
  168. Only valid for Numbers and time.Time types, this will validate the field value
  169. against another fields value either within a struct or passed in field.
  170. usage examples are for validation of a Start and End date:
  171. Validation on End field using ValidateByStruct Usage(gtfield=Start)
  172. Validating by field ValidateFieldByTagAndValue(start, end, "gtfield")
  173. gtefield
  174. Only valid for Numbers and time.Time types, this will validate the field value
  175. against another fields value either within a struct or passed in field.
  176. usage examples are for validation of a Start and End date:
  177. Validation on End field using ValidateByStruct Usage(gtefield=Start)
  178. Validating by field ValidateFieldByTagAndValue(start, end, "gtefield")
  179. ltfield
  180. Only valid for Numbers and time.Time types, this will validate the field value
  181. against another fields value either within a struct or passed in field.
  182. usage examples are for validation of a Start and End date:
  183. Validation on End field using ValidateByStruct Usage(ltfield=Start)
  184. Validating by field ValidateFieldByTagAndValue(start, end, "ltfield")
  185. ltefield
  186. Only valid for Numbers and time.Time types, this will validate the field value
  187. against another fields value either within a struct or passed in field.
  188. usage examples are for validation of a Start and End date:
  189. Validation on End field using ValidateByStruct Usage(ltefield=Start)
  190. Validating by field ValidateFieldByTagAndValue(start, end, "ltefield")
  191. alpha
  192. This validates that a strings value contains alpha characters only
  193. (Usage: alpha)
  194. alphanum
  195. This validates that a strings value contains alphanumeric characters only
  196. (Usage: alphanum)
  197. numeric
  198. This validates that a strings value contains a basic numeric value.
  199. basic excludes exponents etc...
  200. (Usage: numeric)
  201. hexadecimal
  202. This validates that a strings value contains a valid hexadecimal.
  203. (Usage: hexadecimal)
  204. hexcolor
  205. This validates that a strings value contains a valid hex color including
  206. hashtag (#)
  207. (Usage: hexcolor)
  208. rgb
  209. This validates that a strings value contains a valid rgb color
  210. (Usage: rgb)
  211. rgba
  212. This validates that a strings value contains a valid rgba color
  213. (Usage: rgba)
  214. hsl
  215. This validates that a strings value contains a valid hsl color
  216. (Usage: hsl)
  217. hsla
  218. This validates that a strings value contains a valid hsla color
  219. (Usage: hsla)
  220. email
  221. This validates that a strings value contains a valid email
  222. This may not conform to all possibilities of any rfc standard, but neither
  223. does any email provider accept all posibilities...
  224. (Usage: email)
  225. url
  226. This validates that a strings value contains a valid url
  227. This will accept any url the golang request uri accepts but must contain
  228. a schema for example http:// or rtmp://
  229. (Usage: url)
  230. uri
  231. This validates that a strings value contains a valid uri
  232. This will accept any uri the golang request uri accepts (Usage: uri)
  233. Validator notes:
  234. regex
  235. a regex validator won't be added because commas and = signs can be part of
  236. a regex which conflict with the validation definitions, although workarounds
  237. can be made, they take away from using pure regex's. Furthermore it's quick
  238. and dirty but the regex's become harder to maintain and are not reusable, so
  239. it's as much a programming philosiphy as anything.
  240. In place of this new validator functions should be created; a regex can be
  241. used within the validator function and even be precompiled for better efficiency
  242. within regexes.go.
  243. And the best reason, you can sumit a pull request and we can keep on adding to the
  244. validation library of this package!
  245. Panics
  246. This package panics when bad input is provided, this is by design, bad code like that should not make it to production.
  247. type Test struct {
  248. TestField string `validate:"nonexistantfunction=1"`
  249. }
  250. t := &Test{
  251. TestField: "Test"
  252. }
  253. myValidator.ValidateStruct(t) // this will panic
  254. */
  255. package validator