# email不合法时 ➜ curl -X POST http://127.0.0.1:8080/valid -d '{"name":"张三","email":"123","age":21}' {"msg":"Key: 'AddUserPost.Email' Error:Field validation for 'Email' failed on the 'email' tag"} # age 不在指定范围时 ➜ curl -X POST http://127.0.0.1:8080/valid -d '{"name":"张三","email":"123@163.com","age":17}' {"msg":"Key: 'AddUserPost.Age' Error:Field validation for 'Age' failed on the 'gte' tag"} # 姓名不填时 ➜ curl -X POST http://127.0.0.1:8080/valid -d '{"name":"","email":"123@163.com","age":20}' {"msg":"Key: 'AddUserPost.Name' Error:Field validation for 'Name' failed on the 'required' tag"}
2.改成中文
2.1 代码
package main import ( "github.com/gin-gonic/gin" "github.com/go-playground/locales/zh" ut "github.com/go-playground/universal-translator" "github.com/go-playground/validator/v10" zhs "github.com/go-playground/validator/v10/translations/zh" ) var ( validate = validator.New() // 实例化验证器 chinese = zh.New() // 获取中文翻译器 uni = ut.New(chinese, chinese) // 设置成中文翻译器 trans, _ = uni.GetTranslator("zh") // 获取翻译字典 ) type User struct { Name string`form:"name" validate:"required,min=3,max=5"` Email string`form:"email" validate:"email"` Age int8`form:"age" validate:"gte=18,lte=20"` }
funcmain() { engine := gin.Default() engine.GET("/language", func(context *gin.Context) { var user User err := context.ShouldBindQuery(&user) if err != nil { context.JSON(500, gin.H{"msg": err}) return } // 注册翻译器 _ = zhs.RegisterDefaultTranslations(validate, trans) // 使用验证器验证 err = validate.Struct(user) if err != nil { if errors, ok := err.(validator.ValidationErrors); ok { // 翻译,并返回 context.JSON(500, gin.H{ "翻译前": errors.Error(), "翻译后": errors.Translate(trans), }) return } } context.JSON(200,gin.H{"msg":"success"}) }) _ = engine.Run() }
2.2 请求
# 不传参数 ➜ curl -X GET http://127.0.0.1:8080/language { "翻译前":"Key: 'User.Name' Error:Field validation for 'Name' failed on the 'required' tag Key: 'User.Email' Error:Field validation for 'Email' failed on the 'email' tag Key: 'User.Age' Error:Field validation for 'Age' failed on the 'gte' tag", "翻译后":{ "User.Age":"Age必须大于或等于18", "User.Email":"Email必须是一个有效的邮箱", "User.Name":"Name为必填字段" } }
Key: 'CustomParam.Pre' Error:Field validation for'Pre' failed on the 'pre' tag
5.在Gin中使用
5.1 代码
package main import ( "github.com/gin-gonic/gin" "github.com/gin-gonic/gin/binding" "github.com/go-playground/validator/v10" "net/http" "time" ) // 定义结构体 type User struct { Name string`form:"name" binding:"required,min=3,max=5" ` BirthDate time.Time `form:"date" binding:"required,birth" time_format:"2006-01-02"` }
// 运行程序 funcmain() { engine := gin.Default() // 注册自定义验证标签:birth if validate,ok := binding.Validator.Engine().(*validator.Validate);ok { validate.RegisterValidation("birth",checkBirthDate) } // 接收请求 engine.GET("/valid", func(context *gin.Context) { var user User // 集成验证 err := context.ShouldBindQuery(&user) if err != nil { context.JSON(http.StatusBadRequest,gin.H{"error":err.Error()}) return } context.JSON(http.StatusOK,gin.H{"msg":"success"}) }) _ = engine.Run() } // 检测生日 funccheckBirthDate(fl validator.FieldLevel)bool { t,ok := fl.Field().Interface().(time.Time) if ok { // 当前时间应该大于生日时间 if time.Now().After(t) { returntrue } } returnfalse }
5.2 请求返回
# name错误时 ➜ curl -X GET http://127.0.0.1:8080/valid?name=张三&date=2020-01-01 {"error":"Key: 'User.Name' Error:Field validation for 'Name' failed on the 'min' tag"} # 自定义birth格式错误时 ➜ curl -X GET http://127.0.0.1:8080/valid?name=张是三&date=2020 {"error":"parsing time \"2020\" as \"2006-01-02\": cannot parse \"\" as \"-\""} # 都正确 ➜ curl -X GET http://127.0.0.1:8080/valid?name=张是三&date=2020-10-10 {"msg":"success"}
6. 报错显示json tag
.... // 注册一个获取json tag的自定义方法 validate.RegisterTagNameFunc(func(field reflect.StructField)string { splitN := strings.SplitN(field.Tag.Get("json"), ",", 2) fmt.Println(splitN) n := splitN[0] if n == "-" { return"" } return n }) err := validate.Struct(s) if err != nil { .... }