main.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package main
  2. import (
  3. "fmt"
  4. "gopkg.in/go-playground/validator.v9"
  5. )
  6. // User contains user information
  7. type User struct {
  8. FirstName string `validate:"required"`
  9. LastName string `validate:"required"`
  10. Age uint8 `validate:"gte=0,lte=130"`
  11. Email string `validate:"required,email"`
  12. FavouriteColor string `validate:"iscolor"` // alias for 'hexcolor|rgb|rgba|hsl|hsla'
  13. Addresses []*Address `validate:"required,dive,required"` // a person can have a home and cottage...
  14. }
  15. // Address houses a users address information
  16. type Address struct {
  17. Street string `validate:"required"`
  18. City string `validate:"required"`
  19. Planet string `validate:"required"`
  20. Phone string `validate:"required"`
  21. }
  22. // use a single instance of Validate, it caches struct info
  23. var validate *validator.Validate
  24. func main() {
  25. validate = validator.New()
  26. validateStruct()
  27. validateVariable()
  28. }
  29. func validateStruct() {
  30. address := &Address{
  31. Street: "Eavesdown Docks",
  32. Planet: "Persphone",
  33. Phone: "none",
  34. }
  35. user := &User{
  36. FirstName: "Badger",
  37. LastName: "Smith",
  38. Age: 135,
  39. Email: "Badger.Smith@gmail.com",
  40. FavouriteColor: "#000-",
  41. Addresses: []*Address{address},
  42. }
  43. // returns nil or ValidationErrors ( []FieldError )
  44. err := validate.Struct(user)
  45. if err != nil {
  46. // this check is only needed when your code could produce
  47. // an invalid value for validation such as interface with nil
  48. // value most including myself do not usually have code like this.
  49. if _, ok := err.(*validator.InvalidValidationError); ok {
  50. fmt.Println(err)
  51. return
  52. }
  53. for _, err := range err.(validator.ValidationErrors) {
  54. fmt.Println(err.Namespace())
  55. fmt.Println(err.Field())
  56. fmt.Println(err.StructNamespace()) // can differ when a custom TagNameFunc is registered or
  57. fmt.Println(err.StructField()) // by passing alt name to ReportError like below
  58. fmt.Println(err.Tag())
  59. fmt.Println(err.ActualTag())
  60. fmt.Println(err.Kind())
  61. fmt.Println(err.Type())
  62. fmt.Println(err.Value())
  63. fmt.Println(err.Param())
  64. fmt.Println()
  65. }
  66. // from here you can create your own error messages in whatever language you wish
  67. return
  68. }
  69. // save user to database
  70. }
  71. func validateVariable() {
  72. myEmail := "joeybloggs.gmail.com"
  73. errs := validate.Var(myEmail, "required,email")
  74. if errs != nil {
  75. fmt.Println(errs) // output: Key: "" Error:Field validation for "" failed on the "email" tag
  76. return
  77. }
  78. // email ok, move on
  79. }