Gin: Required binding tags on bool fields do not work as expected

Created on 16 Aug 2016  路  2Comments  路  Source: gin-gonic/gin

I'm attempting to enforce required JSON request fields using the binding="required" tag. I expected c.BindJSON to raise an error when a required field was not present, however, it also raises an error when a required bool field is set to false.

Is there a better way to enforce required JSON request bodies?

Here is an example:

func myHandler(c *gin.Context) {
    var req struct {
        Foo string `json:"foo" binding="required"`
        Bar bool   `json:"bar" binding="required"`
    }

    if err := c.BindJSON(&req); err != nil {
        // When a request's `foo` field is set to `false`, the following error is raised:
        // err="Key: '.Foo' Error:Field validation for 'Foo' failed on the 'required' tag"
    }
}

Most helpful comment

Just an update to whomever is still stuck with this bug. Addind *bool is not the entire solution. You must change the binding:"required" to binding:"exists".

Here is the documentation to back that up (gin uses this pkg for input obj validations):
https://godoc.org/gopkg.in/go-playground/validator.v8#hdr-Exists

All 2 comments

Looks like using a *bool will produce the desired behavior.

This may be worthwhile documenting somewhere in the examples.

Just an update to whomever is still stuck with this bug. Addind *bool is not the entire solution. You must change the binding:"required" to binding:"exists".

Here is the documentation to back that up (gin uses this pkg for input obj validations):
https://godoc.org/gopkg.in/go-playground/validator.v8#hdr-Exists

Was this page helpful?
0 / 5 - 0 ratings

Related issues

iiinsomnia picture iiinsomnia  路  3Comments

mastrolinux picture mastrolinux  路  3Comments

rawoke083 picture rawoke083  路  3Comments

wangcn picture wangcn  路  3Comments

ghost picture ghost  路  3Comments