Home > other >  Gin not binding validation in array nested struct
Gin not binding validation in array nested struct

Time:10-07

I have a problem. This problem is about validation binding in gin framework (golang). If I request for an endpoint with (request below) has result success, my expectation is to show error validation. I have tried using pointer in []PatokInputReposisi to *[]PatokInputReposisi and it does nothing work.

My request (JSON):

{
    "date": "2020-01-29T14:47:43.511Z",
    "pitwd": "PIT",
    "area": "RTN",
    "sector": "JL. ILJIN",
    "position": "ES",
    "patoks": [
        {
            "northing": -1.00
        }
    ]
} 

Type struct definition:

type InputReposisiMonitoringRequest struct {
    Date     time.Time            `json:"date" binding:"required"`
    PitWD    string               `json:"pitwd" binding:"required"`
    Area     string               `json:"area" binding:"required"`
    Sector   string               `json:"sector" binding:"required"`
    Position string               `json:"position" binding:"required"`
    Patoks   []PatokInputReposisi `json:"patoks" binding:"required"`
}

type PatokInputReposisi struct {
    Northing  float64 `json:"northing" binding:"required"`
    Easting   float64 `json:"easting" binding:"required"`
    Elevation float64 `json:"elevation" binding:"required"`
    IsSkip    bool    `json:"is_skip" binding:"required"`
}

In handler:

func (h *Handler) handleInputReposisiPatok(c *gin.Context) {
    var request InputReposisiMonitoringRequest
    if err := c.ShouldBindJSON(&request); err != nil {
        c.JSON(http.StatusBadRequest, utils.ErrorResponse(err))
        return
    }
    c.JSON(http.StatusOK, utils.Response("success"))
}

CodePudding user response:

With slice of items use dive

type InputReposisiMonitoringRequest struct {
    Date     time.Time            `json:"date" binding:"required"`
    PitWD    string               `json:"pitwd" binding:"required"`
    Area     string               `json:"area" binding:"required"`
    Sector   string               `json:"sector" binding:"required"`
    Position string               `json:"position" binding:"required"`
    Patoks   []PatokInputReposisi `json:"patoks" binding:"required,dive"`
}

CodePudding user response:

For validating with required, like in your example, and also the nested items, set struct tag to this:

Patoks   []PatokInputReposisi `json:"patoks" binding:"required,dive"`

When you use just dive, it does not validate the empty/nil slice. And if you place required after dive, it applies required to the elements, and not to the slice itself.

  • Related