I read this example from official docs: https://gin-gonic.com/docs/examples/custom-validators/
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,gtfield=CheckIn,bookabledate" 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()})
}
}
And I try to apply time_format tag to my struct ``` package teacher_form
import "time"
type CreateTeacherFormRequest struct {
Birth time.Time json:"birth" form:"birth" binding:"required" time_format:"2006-01-02"
}
```
When I send POST request using formData , the validation work well. But if I send POST request with json payload. Gin fw not validate anything at all. It seem like the time_format only work with formData? How can I validate POST request input field with the specific time format. For example just only date: 2006-01-02.
Comment From: RedCrazyGhost
Since golang json uses the RFC3339
specification, you can access it with the following request parameters
{
"birth":"2024-06-17T15:04:05+08:00"
}
see https://github.com/gin-gonic/gin/issues/1193