为了账号安全,请及时绑定邮箱和手机立即绑定

Undefined validation function 'bookabledate' on field 'CheckIn'

Undefined validation function 'bookabledate' on field 'CheckIn'

有没有报这个错的,win

正在回答

4 回答

老師好厲害,逃不過您的法眼~~祖國的慕課網太棒了~所以每天都來學習

kei

0 回复 有任何疑惑可以回复我~

最新版本,到底是要写binding还是validate呢?gin框架文档写的binding,validator文档写的是validate

0 回复 有任何疑惑可以回复我~

试了很多版本都没有成功,最后试了一下官网的实例: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"}%

能出来结果,可能是版之前的兼容性问题。先这么着吧。

0 回复 有任何疑惑可以回复我~
#1

errorgroup

bingding 改成 validate 就可以了,mac版本
2021-06-30 回复 有任何疑惑可以回复我~
#2

errorgroup 回复 errorgroup

但是规则验证就失效了
2021-06-30 回复 有任何疑惑可以回复我~
type Booking struct

里把binding改成validate

0 回复 有任何疑惑可以回复我~
#1

日落梧桐 提问者

不是这个原因
2021-03-31 回复 有任何疑惑可以回复我~
#2

errorgroup 回复 日落梧桐 提问者

上面的程序在mac上,把binding改成validate就是可以的
2021-06-30 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消
Gin入门实战
  • 参与学习       15924    人
  • 解答问题       55    个

会基础就能上手golang web教程-Gin

进入课程

Undefined validation function 'bookabledate' on field 'CheckIn'

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信