validator

最后更新于:2022-04-02 02:39:57

[TOC] > [github](https://github.com/go-playground/validator) ## 安装 `go get github.com/go-playground/validator/v10` ## 实例 ### 变量验证 ``` validate := validator.New() myEmail := "joeybloggs.gmail.com" errs := validate.Var(myEmail, "required,email") if errs != nil { fmt.Println(errs) // output: Key: "" Error:Field validation for "" failed on the "email" tag return } ``` ### struct 验证
详情 ``` type User struct { FirstName string `validate:"required"` LastName string `validate:"required"` Age uint8 `validate:"gte=0,lte=130"` Email string `validate:"required,email"` FavouriteColor string `validate:"iscolor"` // alias for 'hexcolor|rgb|rgba|hsl|hsla' Addresses []*Address `validate:"required,dive,required"` // a person can have a home and cottage... } // Address houses a users address information type Address struct { Street string `validate:"required"` City string `validate:"required"` Planet string `validate:"required"` Phone string `validate:"required"` } var validate *validator.Validate func main() { validate = validator.New() address := &Address{ Street: "Eavesdown Docks", Planet: "Persphone", Phone: "none", } user := &User{ FirstName: "Badger", LastName: "Smith", Age: 135, Email: "Badger.Smith@gmail.com", FavouriteColor: "#000", Addresses: []*Address{address}, } err := validate.Struct(user) if err != nil { if _, ok := err.(*validator.InvalidValidationError); ok { fmt.Println(err) return } errors := err.(validator.ValidationErrors) fmt.Printf("%+v\n\n",errors.Error()) // 以 Age 举例 for _, err := range errors { fmt.Printf("%+v\n",err) // Key: 'User.Age' Error:Field validation for 'Age' failed on the 'lte' tag fmt.Println(err.Namespace()) // User.Age fmt.Println(err.Field()) // Age fmt.Println(err.StructNamespace()) // User.Age fmt.Println(err.StructField()) // Age fmt.Println(err.Tag()) // lte fmt.Println(err.ActualTag()) // lte fmt.Println(err.Kind()) // uint8 fmt.Println(err.Type()) // uint8 fmt.Println(err.Value()) // 135 fmt.Println(err.Param()) // 130 fmt.Println() } return } } ```

## 自定义错误,与国际化
详情 ```package main import ( "fmt" "github.com/go-playground/locales/en" "github.com/go-playground/locales/zh" "github.com/go-playground/universal-translator" "github.com/go-playground/validator/v10" vten "github.com/go-playground/validator/v10/translations/en" vtzh "github.com/go-playground/validator/v10/translations/zh" ) type User struct { FistName string `validate:"required"` LastName string `validate:"required"` Age int `validate:"gte=0,lte=130"` Email string `validate:"required,email"` } var validate *validator.Validate var tranEn ut.Translator var tranCn ut.Translator func main() { user :=User{ FistName:"fitstname", LastName:"lastname", Age:131, Email:"222222q.com", } validate = validator.New() cn := zh.New() en := en.New() uni :=ut.New(cn,cn,en) // 设置默认英文 tranEn, found := uni.GetTranslator("en") if found { err := vten.RegisterDefaultTranslations(validate, tranEn) if err != nil { fmt.Println(err) } }else{ panic("not found") } // 设置默认中文 transZH, found := uni.GetTranslator("zh") if found { err := vtzh.RegisterDefaultTranslations(validate, transZH) if err != nil { fmt.Println(err) } }else{ panic("not found") } //替换原有错误提示 validate.RegisterTranslation("lte", transZH, func(ut ut.Translator) error { return ut.Add("lte", "{0} 不能大于 130 啊!!!", true) // Age必须小于或等于130 -> Age 不能大于 130 啊!!! }, func(ut ut.Translator, fe validator.FieldError) string { t, _ := ut.T("lte", fe.Field()) return t }) err := validate.Struct(user) if err != nil { _,ok:= err.(*validator.InvalidValidationError) if ok { fmt.Println(err) } errs,ok:=err.(validator.ValidationErrors) if ok { for _,err:=range errs{ fmt.Println(err.Translate(tranEn)) // Email must be a valid email address fmt.Println(err.Translate(transZH)) // Email必须是一个有效的邮箱 } } } } ```

';