日落梧桐
2021-03-24 12:22
Undefined validation function 'bookabledate' on field 'CheckIn'
有没有报这个错的,win
最新版本,到底是要写binding还是validate呢?gin框架文档写的binding,validator文档写的是validate
试了很多版本都没有成功,最后试了一下官网的实例:https://github.com/gin-gonic/gin#custom-validators
package main import ( "net/http" "time" "github.com/gin-gonic/gin" "github.com/gin-gonic/gin/binding" "github.com/go-playground/validator" ) // Booking contains binded and validated data. type Booking struct { CheckIn time.Time `form:"check_in" binding:"required,bookabledate" time_format:"2006-01-02"` CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02"` } 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() if v, ok := binding.Validator.Engine().(*validator.Validate); ok { v.RegisterValidation("bookabledate", bookableDate) } 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 { c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) } }
import 有一点改动,没有加/v10,看了一下源文件是v10的,就去掉了
import "github.com/go-playground/validator"
然后运行
$ curl "http://127.0.0.1:8085/bookable?check_in=2021-04-02&check_out=2021-04-07" {"message":"Booking dates are valid!"} $ curl "http://127.0.0.1:8085/bookable?check_in=2021-04-09&check_out=2021-04-07" {"error":"Key: 'Booking.CheckOut' Error:Field validation for 'CheckOut' failed on the 'gtfield' tag"} $ curl "http://127.0.0.1:8085/bookable?check_in=2021-04-01&check_out=2021-04-07" {"error":"Key: 'Booking.CheckIn' Error:Field validation for 'CheckIn' failed on the 'bookabledate' tag"}%
能出来结果,可能是版之前的兼容性问题。先这么着吧。
type Booking struct
里把binding改成validate
Gin入门实战
15937 学习 · 55 问题
相似问题