customer_tag.go:
package main import ( "fmt" "github.com/go-playground/validator/v10" ) type User struct { Name string `form:"name" json:"name" validate:"required,CustomerValidation"` //注意:required和CustomerValidation之间不能有空格,否则panic。CustomerValidation:自定义tag-函数标签 Age uint8 ` form:"age" json:"age" validate:"gte=0,lte=80"` //注意:gte=0和lte=80之间不能有空格,否则panic } var validate *validator.Validate func main() { validate = validator.New() validate.RegisterValidation("CustomerValidation", CustomerValidationFunc) //注册自定义函数,前一个参数是struct里tag自定义,后一个参数是自定义的函数 user := &User{ Name: "jimmy", Age: 86, } fmt.Println("first value: ", user) err := validate.Struct(user) if err != nil { fmt.Printf("Err(s):\n%+v\n", err) } user.Name = "tom" user.Age = 29 fmt.Println("second value: ", user) err = validate.Struct(user) if err != nil { fmt.Printf("Err(s):\n%+v\n", err) } } // 自定义函数 func CustomerValidationFunc(f1 validator.FieldLevel) bool { // f1 包含了字段相关信息 // f1.Field() 获取当前字段信息 // f1.Param() 获取tag对应的参数 // f1.FieldName() 获取字段名称 return f1.Field().String() == "jimmy" }运行输出:
$ go run customer.go
first value: &{jimmy 86}
Err(s):
Key: 'User.Age' Error:Field validation for 'Age' failed on the 'lte' tag
second value: &{tom 29}
Err(s):
Key: 'User.Name' Error:Field validation for 'Name' failed on the 'CustomerValidation' tag
**注意:
上面代码user struct定义中 ,validate里的required和CustomerValidation之间不能有空格,否则运行时报panic错误:panic: Undefined validation function ' CustomerValidation' on field 'Name'
例子4:自定义函数-直接注册函数1不通过字段tag自定义函数,直接注册函数。
RegisterStructValidationhttps://github.com/go-playground/validator/blob/master/_examples/struct-level/main.go
customer1.go
package main import ( "fmt" "github.com/go-playground/validator/v10" ) type User struct { FirstName string `json:firstname` LastName string `json:lastname` Age uint8 `validate:"gte=0,lte=130"` Email string `validate:"required,email"` FavouriteColor string `validate:"hexcolor|rgb|rgba"` } var validate *validator.Validate func main() { validate = validator.New() validate.RegisterStructValidation(UserStructLevelValidation, User{}) user := &User{ FirstName: "", LastName: "", Age: 30, Email: "TestFunc@126.com", FavouriteColor: "#000", } err := validate.Struct(user) if err != nil { fmt.Println(err) } } func UserStructLevelValidation(sl validator.StructLevel) { user := sl.Current().Interface().(User) if len(user.FirstName) == 0 && len(user.LastName) == 0 { sl.ReportError(user.FirstName, "FirstName", "firstname", "firstname", "") sl.ReportError(user.LastName, "LastName", "lastname", "lastname", "") } }运行输出:
$ go run customer1.go
Key: 'User.FirstName' Error:Field validation for 'FirstName' failed on the 'firstname' tag
Key: 'User.LastName' Error:Field validation for 'LastName' failed on the 'lastname' tag
https://github.com/go-playground/validator/blob/master/_examples/custom/main.go
:验证类型的自定义函数
customer2.go:
package main import ( "database/sql" "database/sql/driver" "fmt" "reflect" "github.com/go-playground/validator/v10" ) type DbBackedUser struct { Name sql.NullString `validate:"required"` Age sql.NullInt64 `validate:"required"` } var validate *validator.Validate func main() { validate = validator.New() validate.RegisterCustomTypeFunc(ValidateValuer, sql.NullString{}, sql.NullInt64{}, sql.NullBool{}, sql.NullFloat64{}) // build object for validation x := DbBackedUser{Name: sql.NullString{String: "", Valid: true}, Age: sql.NullInt64{Int64: 0, Valid: false}} err := validate.Struct(x) if err != nil { fmt.Printf("Err(s):\n%+v\n", err) } } func ValidateValuer(field reflect.Value) interface{} { if valuer, ok := field.Interface().(driver.Valuer); ok { val, err := valuer.Value() if err == nil { return val } // handle the error how you want } return nil }运行输出:
$ go run customer.go
Err(s):
Key: 'DbBackedUser.Name' Error:Field validation for 'Name' failed on the 'required' tag
Key: 'DbBackedUser.Age' Error:Field validation for 'Age' failed on the 'required' tag
注意,这个函数:
,它上面有2行注释:
// RegisterCustomTypeFunc registers a CustomTypeFunc against a number of types
//
// NOTE: this method is not thread-safe it is intended that these all be registered prior to any validation
它是一个验证数据类型自定义函数,NOTE:这个方法不是线程安全的