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 } } ```## 自定义错误,与国际化