Gin: Bool binding required Bug

Created on 21 Feb 2017  路  4Comments  路  Source: gin-gonic/gin

Hi guys. I have the following problem

type Foo struct {
    Bar bool `json:"bar" binding:"required"` // True / False
}

When I send a JSON request with the value true it works, but when I send the same request with false I get the following error.

{
    "error": {
        "Foo.Bar": {
            "FieldNamespace": "Foo.Bar",
                "NameNamespace": "Bar",
            "Field": "Bar",
            "Name": "Bar",
            "Tag": "required",
            "ActualTag": "required",
            "Kind": 1,
            "Type": {},
            "Param": "",
            "Value": false
        }
    }
},

Most helpful comment

Thanks @bkeyoumarsi

to further this answer exists was removed in v9 and required works with *bool

I highly recommend updating to v9, there were many performance updates and changes for ease of use :)

see https://github.com/go-playground/validator/tree/v9/examples/gin-upgrading-overriding for updating gin to use v9 of validator.

All 4 comments

I'll refer you to:

685

611

In summary you need a pointer or custom type to know if the value exists due to Go's static nature.

Change bool to *bool

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

Thanks @bkeyoumarsi

to further this answer exists was removed in v9 and required works with *bool

I highly recommend updating to v9, there were many performance updates and changes for ease of use :)

see https://github.com/go-playground/validator/tree/v9/examples/gin-upgrading-overriding for updating gin to use v9 of validator.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

mastrolinux picture mastrolinux  路  3Comments

CodingPapi picture CodingPapi  路  3Comments

rawoke083 picture rawoke083  路  3Comments

mdnight picture mdnight  路  3Comments

lilee picture lilee  路  3Comments