var validate *validator.Validate = validator.New()
type User struct { Name string`validate:"required"` Age int`validate:"required"` }
type Addr struct { City string Street string }
funcTestValidateStruct1(t *testing.T) { user := User{} err := validate.Struct(user) if err != nil { // Key: 'User.Name' Error:Field validation for 'Name' failed on the 'required' tag // Key: 'User.Age' Error:Field validation for 'Age' failed on the 'required' tag fmt.Println(err) } }
var mapone map[string]string mapone = map[string]string{"one": "jimmmy", "two": "tom", "three": ""} err = validate.Var(mapone, "gte=3,dive,keys,eq=1|eq=2,endkeys,required") if err != nil { // Key: '[one]' Error:Field validation for '[one]' failed on the 'eq=1|eq=2' tag // Key: '[two]' Error:Field validation for '[two]' failed on the 'eq=1|eq=2' tag // Key: '[three]' Error:Field validation for '[three]' failed on the 'eq=1|eq=2' tag // Key: '[three]' Error:Field validation for '[three]' failed on the 'required' tag fmt.Println(err) }
var validate *validator.Validate = validator.New()
type User struct { Name string`json:"name_json" form:"name_form" validate:"required"` Age int`json:"age_json" form:"age_form" validate:"required"` }
funcTestValidateStruct1(t *testing.T) { user := User{} err := validate.Struct(user) if err != nil { // Key: 'User.Name' Error:Field validation for 'Name' failed on the 'required' tag // Key: 'User.Age' Error:Field validation for 'Age' failed on the 'required' tag fmt.Println(err) } }
// 注册一个获取json tag的自定义方法 validate.RegisterTagNameFunc(func(fld reflect.StructField)string { name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0] // skip if tag key says it should be ignored if name == "-" { return"" } return name })
funcTestValidateStruct1(t *testing.T) { user := User{} err := validate.Struct(user) if err != nil { // Key: 'User.name_json' Error:Field validation for 'name_json' failed on the 'required' tag // Key: 'User.age_json' Error:Field validation for 'age_json' failed on the 'required' tag fmt.Println(err) } }
user := User{"zhangsan", 30} err := validate.Struct(user) if err != nil { // Key: 'User.Name' Error:Field validation for 'Name' failed on the 'check_name' tag fmt.Println(err) }
user := User{"zha", 30} err := validate.Struct(user) if err != nil { // Key: 'User.fname' Error:Field validation for 'fname' failed on the 'fnameorlname' tag fmt.Println(err) }