- With issues:
- Use the search tool before opening a new issue.
- Please provide source code and commit sha if you found a bug.
- Review existing issues and provide feedback or react to them.
Description
I'm currently trying to validate the request body with ShouldBindJSON
and I'm sending a random JSON body (ex. {"a":"a"}
-which is the one I'm using btw-) and it returns no error
How to reproduce
My struct:
type UserSignUp struct {
Username string `json:"username"`
Password string `json:"password"`
Email string `json:"email"`
}
The code that implements the validation
var dto register.UserSignUp
if err := c.ShouldBindJSON(&dto); err != nil {
// do something
}
Expectations
An error
Actual result
No error
Environment
- go version:go version go1.13.6 windows/amd64
- gin version (or commit ref):github.com/gin-gonic/gin v1.5.0
- operating system:Windows 10
Comment From: linvis
hi, ShouldBindJSON is based on encoding/json
,
and encoding/json
doesn't support to check if a field is existed
see this issus for why not support: https://github.com/golang/go/issues/17163
so if you really need it, you could do it by yourself
Comment From: whatvn
if you want to return error on invalid input, use validator
type UserSignUp struct {
Username string `json:"username" binding:"required"`
Password string `json:"password"`
Email string `json:"email"`
}
Comment From: appleboy
See https://github.com/gin-gonic/gin#model-binding-and-validation or https://gin-gonic.com/docs/examples/custom-validators/
Comment From: umermansoor
type UserSignUp struct {
Username string `json:"username" binding:"required"`
Password string `json:"password"`
Email string `json:"email"`
}
Is there any easy way to error when extraneous fields are present i.e. in this case the request body is: {"username": "123", "a":"a"}
?