Home > Net >  golang/gin number validation binding
golang/gin number validation binding

Time:12-14

Ok so I'm using a go-gin tutorial for json validation, but the weird thing happen when trying to validate a number, I have this kind of struct

type BookInput struct{  
    Title string    `json:"title" binding:"required"`   
    Price int `json:"price" binding:"required,numeric"` 
}

and main handler

func postbooksHandler(c *gin.Context){
    var bookInput BookInput

    err := c.ShouldBindJSON(&bookInput)

    if err != nil {
        
        for _,e := range err.(validator.ValidationErrors){
            errorMessage := fmt.Sprintf("error on field %s, condition : %s",e.Field(),e.ActualTag())
            c.JSON(http.StatusBadRequest,errorMessage)
            return
        }
        
        return
    } 

    c.JSON(http.StatusOK,gin.H{
        "title" : bookInput.Title,
        "price" : bookInput.Price,
    })
}

Then it return error :

interface conversion: error is *json.UnmarshalTypeError, not validator.ValidationErrors

then the tutorial solve it by changing the type struct to

type BookInput struct{  
        Title string    `json:"title" binding:"required"`   
        Price json.Number `json:"price" binding:"required,numeric"` 
    }

which solve the string input validation for him, but mine give :

interface conversion: error is *errors.errorString, not validator.ValidationErrors

And I have no idea when it go wrong, and in the comment section there's someone who have the problem too and someone suggest using Price interface{} that does solve it ( by tweaking it with converting the interface to int) , And I'm curious if there any other solution for it? (to keep the model input have a clear type instead of interface). Thanks in advance

CodePudding user response:

You should check the type of error before referring to that. Get the error value using ok-value pattern first.

e,ok:= err.(validator.ValidationErrors)
if ok{
// it is a validation error and you can handle it.
}else{
// it is another error and you should handle it.
}

CodePudding user response:

print the error then you will know what went wrong

fmt.Printf("error %v", err)
// json: cannot unmarshal number 5.0 into Go struct field BookInput.price of type int

price=5.0 x

price='4' x

price=5 ⎷

price=-5 ⎷

  • Related