Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Required binding tags on bool fields do not work as expected #685

Closed
bndw opened this issue Aug 16, 2016 · 3 comments
Closed

Required binding tags on bool fields do not work as expected #685

bndw opened this issue Aug 16, 2016 · 3 comments

Comments

@bndw
Copy link

bndw commented Aug 16, 2016

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"
    }
}
@bndw
Copy link
Author

bndw commented Aug 16, 2016

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

This may be worthwhile documenting somewhere in the examples.

@qeubar
Copy link

qeubar commented Apr 18, 2017

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

@sneakycrowllc
Copy link

sneakycrowllc commented May 7, 2021

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

If you're using v9 and you need to require a bool, just use *bool (no binding:"exists" necessary, binding:"required" will work)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants