2

I just would like to do like the below about validation on Gin(Golang).

type Accounts struct {
    Accounts []*Account `json:"accounts" binding:"required,dive"`
}

type Account struct {
    BusinessId string `json:"business_id" binding:"required,min=1,max=50"`
    Token  string `json:"token" binding:"required,min=1,max=100"`
    UserId     string `json:"user_id" binding:"required,min=1,max=50"`
}
import (
    "reflect"

    "github.com/gin-gonic/gin"
    "github.com/gin-gonic/gin/binding"

    "github.com/go-playground/validator/v10"
)

func Validator(c *gin.Context, request interface{}) (interface{}, []string) {
    var err []string

    errors := c.ShouldBind(&request)

    if errors != nil {
        var messages []string
        for _, m := range errors.(validator.ValidationErrors).Translate(t) {

            messages = append(messages, m)

        }

        err = messages

    }

    return request, err
}

_, errors := pkg.Validator(c, Accounts{})

    if errors != nil {

        exceptions.Validation(errors, c)
        return
    }

Why doesn’t work? Please teach me how works.

I would like to validate array on Gin(Golang). I tried to use 'dive', but it looks like not working.

TomoEno
  • 21
  • 1
  • 1
    Pass a pointer to the validator: `pkg.Validator(c, &Accounts{})`. And you can omit the address operator from the call to should bind: `c.ShouldBind(request)`. – mkopriva Feb 27 '23 at 12:55
  • 1
    to mkopriva Thank you so much!!! It works. – TomoEno Feb 27 '23 at 14:05

0 Answers0