6 "gopkg.in/go-playground/validator.v9"
9 // User contains user information
11 FirstName string `validate:"required"`
12 LastName string `validate:"required"`
13 Age uint8 `validate:"gte=0,lte=130"`
14 Email string `validate:"required,email"`
15 FavouriteColor string `validate:"iscolor"` // alias for 'hexcolor|rgb|rgba|hsl|hsla'
16 Addresses []*Address `validate:"required,dive,required"` // a person can have a home and cottage...
19 // Address houses a users address information
21 Street string `validate:"required"`
22 City string `validate:"required"`
23 Planet string `validate:"required"`
24 Phone string `validate:"required"`
27 // use a single instance of Validate, it caches struct info
28 var validate *validator.Validate
32 validate = validator.New()
38 func validateStruct() {
41 Street: "Eavesdown Docks",
50 Email: "Badger.Smith@gmail.com",
51 FavouriteColor: "#000-",
52 Addresses: []*Address{address},
55 // returns nil or ValidationErrors ( map[string]*FieldError )
56 err := validate.Struct(user)
59 // this check is only needed when your code could produce
60 // an invalid value for validation such as interface with nil
61 // value most including myself do not usually have code like this.
62 if _, ok := err.(*validator.InvalidValidationError); ok {
67 for _, err := range err.(validator.ValidationErrors) {
69 fmt.Println(err.Namespace())
70 fmt.Println(err.Field())
71 fmt.Println(err.StructNamespace()) // can differ when a custom TagNameFunc is registered or
72 fmt.Println(err.StructField()) // by passing alt name to ReportError like below
73 fmt.Println(err.Tag())
74 fmt.Println(err.ActualTag())
75 fmt.Println(err.Kind())
76 fmt.Println(err.Type())
77 fmt.Println(err.Value())
78 fmt.Println(err.Param())
82 // from here you can create your own error messages in whatever language you wish
86 // save user to database
89 func validateVariable() {
91 myEmail := "joeybloggs.gmail.com"
93 errs := validate.Var(myEmail, "required,email")
96 fmt.Println(errs) // output: Key: "" Error:Field validation for "" failed on the "email" tag