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
}
}
},
I'll refer you to:
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.
Most helpful comment
Thanks @bkeyoumarsi
to further this answer
existswas removed in v9 andrequiredworks with*boolI 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.