问答详情
源自:2-13 gin基础:验证请求参数 - 自定义验证规则

validator v8升到v9之后代码变成这样,绑定和验证分离了, 不知道写成这样行不行,但是运行还是没问题的

package main

import (
   "github.com/gin-gonic/gin"
   "gopkg.in/go-playground/validator.v9"
   "net/http"
   "time"
)

type Booking struct {
   CheckIn time.Time `form:"check_in" validate:"required,bookableDate" time_format:"2006-01-02"`
   CheckOut time.Time `form:"check_out" validate:"required,gtfield=CheckIn" time_format:"2006-01-02"`
}


func main(){

   r := gin.Default()

   validate := validator.New()
   validate.RegisterValidation("bookableDate", bookableDate)
   r.GET("/bookable", func(c *gin.Context) {
      var book Booking
      if err := c.ShouldBind(&book); err != nil {
         c.JSON(http.StatusInternalServerError, gin.H{
            "error": err.Error(),
         })
         c.Abort()
         return
      }
      if err := validate.Struct(book); err != nil {
         c.JSON(http.StatusInternalServerError, gin.H{
            "error": err.Error(),
         })
         c.Abort()
         return
      }

      c.JSON(http.StatusOK, gin.H{
         "message": "OK",
         "booking": book,
      })
   })

   r.Run()
}

func bookableDate(fl validator.FieldLevel) bool {

   if date, ok := fl.Field().Interface().(time.Time); ok {
      today := time.Now()
      if date.Unix() > today.Unix() {
         return true
      }
   }

   return false
}


提问者:错落3980253 2019-12-04 14:43

个回答

  • 代码的坏味道
    2019-12-09 14:40:25
    已采纳

    对的,V9就是这样用的

  • 杰5245212
    2020-05-25 11:29:47

    {"error":"Key: 'Booking.CheckIn' Error:Field validation for 'CheckIn' failed on the 'bookableDate' tag"}w

  • 江山快手
    2020-04-04 17:11:19

    Undefined validation function 'bookableDate' on field 'CheckIn'

  • yuzhewo
    2020-03-31 16:45:01

    为啥我的代码 此处传过来的时间恒为 2012-04-01 00:00:00 +0800 CST