Custom Validators

It is also possible to register custom validators. See the example code.

  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. "gopkg.in/go-playground/validator.v8"
  9. )
  10. type Booking struct {
  11. CheckIn time.Time `form:"check_in" binding:"required,bookabledate" time_format:"2006-01-02"`
  12. CheckOut time.Time `form:"check_out" binding:"required,gtfield=CheckIn" time_format:"2006-01-02"`
  13. }
  14. func bookableDate(
  15. v *validator.Validate, topStruct reflect.Value, currentStructOrField reflect.Value,
  16. field reflect.Value, fieldType reflect.Type, fieldKind reflect.Kind, param string,
  17. ) bool {
  18. if date, ok := field.Interface().(time.Time); ok {
  19. today := time.Now()
  20. if today.Year() > date.Year() || today.YearDay() > date.YearDay() {
  21. return false
  22. }
  23. }
  24. return true
  25. }
  26. func main() {
  27. route := gin.Default()
  28. if v, ok := binding.Validator.Engine().(*validator.Validate); ok {
  29. v.RegisterValidation("bookabledate", bookableDate)
  30. }
  31. route.GET("/bookable", getBookable)
  32. route.Run(":8085")
  33. }
  34. func getBookable(c *gin.Context) {
  35. var b Booking
  36. if err := c.ShouldBindWith(&b, binding.Query); err == nil {
  37. c.JSON(http.StatusOK, gin.H{"message": "Booking dates are valid!"})
  38. } else {
  39. c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
  40. }
  41. }
  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 level validations can also be registed this way.
See the struct-lvl-validation example to learn more.