1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
| type User struct { Name string `binding:"required" validate:"isName,min=6,max=10"` Age uint8 `binding:"required" validate:"gte=1,lte=10"` Sex string `binding:"required" validate:"oneof=female male"` Email string `binding:"required" validate:"email"` }
func isName(fl validator.FieldLevel) bool { if name, ok := fl.Field().Interface().(string); ok { return len(strings.Split(name, " ")) >= 2 } return true }
func main() { validate := validator.New() user := User{Name: "ifan lw", Age: 11} validate.RegisterValidation("isName", isName) err := validate.Struct(user) if err != nil { fmt.Println("校验错误", err) } }
|