(编辑:jimmy 日期: 2024/12/23 浏览:2)
前言
在web应用中经常会遇到数据验证问题,普通的验证方法比较繁琐,这里介绍一个使用比较多的包validator。
原理
将验证规则写在struct对字段tag里,再通过反射(reflect)获取struct的tag,实现数据验证。
安装
go get github.com/go-playground/validator/v10
示例
package main import ( "fmt" "github.com/go-playground/validator/v10" ) type Users struct { Phone string `form:"phone" json:"phone" validate:"required"` Passwd string `form:"passwd" json:"passwd" validate:"required,max=20,min=6"` Code string `form:"code" json:"code" validate:"required,len=6"` } func main() { users := &Users{ Phone: "1326654487", Passwd: "123", Code: "123456", } validate := validator.New() err := validate.Struct(users) if err != nil { for _, err := range err.(validator.ValidationErrors) { fmt.Println(err)//Key: 'Users.Passwd' Error:Field validation for 'Passwd' failed on the 'min' tag return } } return }
验证规则
跨字段验证
如想实现比较输入密码和确认密码是否一致等类似场景
示例
type UserReg struct { Passwd string `form:"passwd" json:"passwd" validate:"required,max=20,min=6"` Repasswd string `form:"repasswd" json:"repasswd" validate:"required,max=20,min=6,eqfield=Passwd"` }
示例验证了Passwd,和Repasswd值是否相等。如想了解更多类型,请参考文档 https://godoc.org/gopkg.in/go-playground/validator.v10
自定义验证类型
示例:
package main import ( "fmt" "github.com/go-playground/validator/v10" ) type Users struct { Name string `form:"name" json:"name" validate:"required,CustomValidationErrors"`//包含自定义函数 Age uint8 `form:"age" json:"age" validate:"required,gt=18"` Passwd string `form:"passwd" json:"passwd" validate:"required,max=20,min=6"` Code string `form:"code" json:"code" validate:"required,len=6"` } func main() { users := &Users{ Name: "admin", Age: 12, Passwd: "123", Code: "123456", } validate := validator.New() //注册自定义函数 _=validate.RegisterValidation("CustomValidationErrors", CustomValidationErrors) err := validate.Struct(users) if err != nil { for _, err := range err.(validator.ValidationErrors) { fmt.Println(err)//Key: 'Users.Name' Error:Field validation for 'Name' failed on the 'CustomValidationErrors' tag return } } return } func CustomValidationErrors(fl validator.FieldLevel) bool { return fl.Field().String() != "admin" }
翻译错误信息为中文
通过以上示例我们看到,validator默认的错误提示信息类似如下
Key: 'Users.Name' Error:Field validation for 'Name' failed on the 'CustomValidationErrors' tag
显然这并不是我们想要,如想翻译成中文,或其他语言怎么办?go-playground上提供了很好的解决方法。
先自行安装需要的两个包
https://github.com/go-playground/locales
https://github.com/go-playground/universal-translator
执行:
go get github.com/go-playground/universal-translator go get github.com/go-playground/locales
示例:
package main import ( "fmt" "github.com/go-playground/locales/zh" ut "github.com/go-playground/universal-translator" "github.com/go-playground/validator/v10" zh_translations "github.com/go-playground/validator/v10/translations/zh" ) type Users struct { Name string `form:"name" json:"name" validate:"required"` Age uint8 `form:"age" json:"age" validate:"required,gt=18"` Passwd string `form:"passwd" json:"passwd" validate:"required,max=20,min=6"` Code string `form:"code" json:"code" validate:"required,len=6"` } func main() { users := &Users{ Name: "admin", Age: 12, Passwd: "123", Code: "123456", } uni := ut.New(zh.New()) trans, _ := uni.GetTranslator("zh") validate := validator.New() //验证器注册翻译器 err := zh_translations.RegisterDefaultTranslations(validate, trans) if err!=nil { fmt.Println(err) } err = validate.Struct(users) if err != nil { for _, err := range err.(validator.ValidationErrors) { fmt.Println(err.Translate(trans))//Age必须大于18 return } } return }
输出:
Age必须大于18
至此我们发现大部分错误信息已经翻译成中文,但字段名(Age)还是没有翻译,为了将字段名翻译成中文,查了一些资料,https://www.jb51.net/article/197866.htm>,
照着做没有成功(可能有遗漏吧),最后还是翻看了一下源代码,在<https://github.com/go-playground/validator/blob/master/validator_instance.go,第137行
// RegisterTagNameFunc registers a function to get alternate names for StructFields. // // eg. to use the names which have been specified for JSON representations of structs, rather than normal Go field names: // // validate.RegisterTagNameFunc(func(fld reflect.StructField) string { // name := strings.SplitN(fld.Tag.Get("json"), ",", 2)[0] // if name == "-" { // return "" // } // return name // })
其实原理就是注册一个函数,将struct tag里添加的中文名 作为备用名。
package main import ( "fmt" "github.com/go-playground/locales/zh" ut "github.com/go-playground/universal-translator" "github.com/go-playground/validator/v10" zh_translations "github.com/go-playground/validator/v10/translations/zh" "reflect" ) type Users struct { Name string `form:"name" json:"name" validate:"required" label:"用户名"` Age uint8 `form:"age" json:"age" validate:"required,gt=18" label:"年龄"` Passwd string `form:"passwd" json:"passwd" validate:"required,max=20,min=6"` Code string `form:"code" json:"code" validate:"required,len=6"` } func main() { users := &Users{ Name: "admin", Age: 12, Passwd: "123", Code: "123456", } uni := ut.New(zh.New()) trans, _ := uni.GetTranslator("zh") validate := validator.New() //注册一个函数,获取struct tag里自定义的label作为字段名 validate.RegisterTagNameFunc(func(fld reflect.StructField) string { name:=fld.Tag.Get("label") return name }) //注册翻译器 err := zh_translations.RegisterDefaultTranslations(validate, trans) if err!=nil { fmt.Println(err) } err = validate.Struct(users) if err != nil { for _, err := range err.(validator.ValidationErrors) { fmt.Println(err.Translate(trans))//年龄必须大于18 return } } return }
输出结果:
年龄必须大于18
gin 内置的validator
gin已经支持go-playground / validator / v10进行验证。在此处查看有关标签用法的完整文档。
以下只提供了一个绑定ShouldBindWith示例,如需了解更多方法,进入这里。
示例
package main import ( "fmt" "github.com/go-playground/locales/zh" ut "github.com/go-playground/universal-translator" "github.com/go-playground/validator/v10" "net/http" "reflect" "strings" "time" "github.com/gin-gonic/gin" "github.com/gin-gonic/gin/binding" zh_translations "github.com/go-playground/validator/v10/translations/zh" ) var trans ut.Translator // Booking contains binded and validated data. type Booking struct { CheckIn time.Time `form:"check_in" json:"check_in" binding:"required,bookabledate" time_format:"2006-01-02" label:"输入时间"` CheckOut time.Time `form:"check_out" json:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02" label:"输出时间"` } var bookableDate validator.Func = func(fl validator.FieldLevel) bool { date, ok := fl.Field().Interface().(time.Time) if ok { today := time.Now() if today.After(date) { return false } } return true } func main() { route := gin.Default() uni := ut.New(zh.New()) trans, _ = uni.GetTranslator("zh") if v, ok := binding.Validator.Engine().(*validator.Validate); ok { //注册翻译器 _= zh_translations.RegisterDefaultTranslations(v, trans) //注册自定义函数 _=v.RegisterValidation("bookabledate", bookableDate) //注册一个函数,获取struct tag里自定义的label作为字段名 v.RegisterTagNameFunc(func(fld reflect.StructField) string { name:=fld.Tag.Get("label") return name }) //根据提供的标记注册翻译 v.RegisterTranslation("bookabledate", trans, func(ut ut.Translator) error { return ut.Add("bookabledate", "{0}不能早于当前时间或{1}格式错误!", true) }, func(ut ut.Translator, fe validator.FieldError) string { t, _ := ut.T("bookabledate", fe.Field(), fe.Field()) return t }) } route.GET("/bookable", getBookable) route.Run(":8085") } func getBookable(c *gin.Context) { var b Booking if err := c.ShouldBindWith(&b, binding.Query); err == nil { c.JSON(http.StatusOK, gin.H{"message": "Booking dates are valid!"}) } else { errs := err.(validator.ValidationErrors) fmt.Println(errs.Translate(trans)) //for _, e := range errs { // // can translate each error one at a time. // fmt.Println(e.Translate(trans)) //} c.JSON(http.StatusBadRequest, gin.H{"error": errs.Translate(trans)}) } }
运行程序,执行以下命令
$ curl "localhost:8085/bookable"
结果:
{"error":{"Booking.输入时间":"输入时间不能早于当前时间或输入时间格式错误!","Booking.输出时间":"输出时间必须大于CheckIn"}}
查看以上结果我们发现翻译还是不太完美,如规则中有gtfield的情况,字段(CheckIn)并没有被翻译。所以通过struct添加label的方式并不能从根本上解决字段翻译问题。为了得到想要的结果,就需要将错误信息做单独处理再输出。
先定义翻译库
var BookingTrans =map[string]string{"CheckIn":"输入时间","CheckOut":"输出时间"}
再定义翻译函数
func TransTagName(libTans,err interface{}) interface{} { switch err.(type) { case validator.ValidationErrorsTranslations: var errs map[string]string errs = make(map[string]string,0) for k,v:=range err.(validator.ValidationErrorsTranslations){ for key,value:=range libTans.(map[string]string) { v=strings.Replace(v,key,value,-1) } errs[k] = v } return errs case string: var errs string for key,value:=range libTans.(map[string]string) { errs=strings.Replace(errs,key,value,-1) } return errs default: return err } }
将原来翻译错误信息的地方
errs.Translate(trans)
修改为
msg:=TransTagName(BookingTrans,errs.Translate(trans)) fmt.Println(msg)
结果
{"error":{"Booking.输入时间":"输入时间不能早于当前时间或输入时间格式错误!","Booking.输出时间":"输出时间必须大于输入时间"}}
小结:
1.gin 已经支持validator最新的v10。
2.validator数据验证顺序struct字段从上往下,单个字段规则(binding:"gt=0,lt=2`),先左后右。
参考:
https://github.com/go-playground/validator
https://github.com/gin-gonic/gin
https://gitissue.com/issues/5d06a73965d56f73569b825f
https://segmentfault.com/a/1190000022527284