自定义验证器

注册自定义验证器,查看示例代码.

  1. package main
  2. import (
  3. "net/http"
  4. "reflect"
  5. "time"
  6. "github.com/gin-gonic/gin"
  7. "github.com/gin-gonic/gin/binding"
  8. "github.com/go-playground/validator/v10"
  9. )
  10. // Booking 包含绑定和验证的数据。
  11. type Booking struct {
  12. CheckIn time.Time `form:"check_in" binding:"required,bookabledate" time_format:"2006-01-02"`
  13. CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn,bookabledate" time_format:"2006-01-02"`
  14. }
  15. var bookableDate validator.Func = func(fl validator.FieldLevel) bool {
  16. date, ok := fl.Field().Interface().(time.Time)
  17. if ok {
  18. today := time.Now()
  19. if today.After(date) {
  20. return false
  21. }
  22. }
  23. return true
  24. }
  25. func main() {
  26. route := gin.Default()
  27. if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
  28. v.RegisterValidation("bookabledate", bookableDate)
  29. }
  30. route.GET("/bookable", getBookable)
  31. route.Run(":8085")
  32. }
  33. func getBookable(c *gin.Context) {
  34. var b Booking
  35. if err := c.ShouldBindWith(&b, binding.Query); err == nil {
  36. c.JSON(http.StatusOK, gin.H{"message": "Booking dates are valid!"})
  37. } else {
  38. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  39. }
  40. }
  1. $ curl "localhost:8085/bookable?check_in=2018-04-16&check_out=2018-04-17"
  2. {"message":"Booking dates are valid!"}
  3. $ curl "localhost:8085/bookable?check_in=2018-03-08&check_out=2018-03-09"
  4. {"error":"Key: 'Booking.CheckIn' Error:Field validation for 'CheckIn' failed on the 'bookabledate' tag"}

结构体级别的验证器 也可以通过其他的方式注册。更多信息请参阅 struct-lvl-validation 示例

Last modified 01.08.2020 : chore: update Custom validators (a39a8b4)