Skip to content

Instantly share code, notes, and snippets.

@ilovejs
Created July 29, 2019 05:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ilovejs/98f11a1a819427ca553cc036dd6d2ac6 to your computer and use it in GitHub Desktop.
Save ilovejs/98f11a1a819427ca553cc036dd6d2ac6 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"gopkg.in/go-playground/validator.v9"
)
// Test ...
type Test struct {
Array []string `validate:"required,gt=0,dive,required"`
Map map[string]string `validate:"required,gt=0,dive,keys,keymax,endkeys,required,max=1000"`
}
// use a single instance of Validate, it caches struct info
var validate *validator.Validate
func main() {
validate = validator.New()
// registering alias so we can see the differences between
// map key, value validation errors
validate.RegisterAlias("keymax", "max=10")
var test Test
// test 1
val(test)
// test 2: nested struct
test.Array = []string{"123451234512"}
// vs: test.Array = []string{""}
// validation 'dive' into k, v of the map
test.Map = map[string]string{"12": "123451234"} //key met max=10 requirement, change to exceeed this length for testing
// vs: test.Map = map[string]string{"123451234512": "123451234"}
val(test)
}
func val(test Test) {
fmt.Println("testing")
err := validate.Struct(test)
fmt.Println(err)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment