用于比较两个字段的自定义验证器



我有两个字段- StartTime和EndTime -它们都是时间类型。时间和它们都在同一个结构中。如何创建一个自定义验证器来确保EndTime在StartTime的24小时内?我有麻烦设置验证器。函数来获取两个字段的值,以便我可以比较它们(我知道怎么做)。

var validEndTime validator.Func = func(fl validator.FieldLevel) bool {
endTime, ok := fl.F().Interface().(time.Time)
if ok {
today := time.Now()
if today.After(date) {
return false
}
}
return true
}

这是我开始编写的示例函数。

您可以使用fl.Parent()来获取结构体

package main
import (
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/go-playground/validator/v10"
)
// 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" time_format:"2006-01-02"`
}
var bookableDate validator.Func = func(fl validator.FieldLevel) bool {
date, ok := fl.Field().Interface().(time.Time)
if ok {
booking, ok2 := fl.Parent().Interface().(*Booking)
if ok2 && booking.CheckOut.Unix() - date.Unix() > 24*3600 {
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()})
}
}

最新更新