Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

time_format tag not work with json tag #3989

Closed
just-pthai-it opened this issue Jun 10, 2024 · 1 comment
Closed

time_format tag not work with json tag #3989

just-pthai-it opened this issue Jun 10, 2024 · 1 comment

Comments

@just-pthai-it
Copy link

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.

@RedCrazyGhost
Copy link
Contributor

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 #1193

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants