gin: Unable to use Number validator
Hi,
It’s possible I just don’t understand how to use the validations correctly, but I am trying to bind this form object:
type Form struct {
Age int `binding:"required,number"`
}
but when testing supplying a string value in the form submission, it errors with an strconv.Atoi error instead of providing a validation error. It looks like it’s failing when converting the data into my Form type, instead of first validating it.
Is there a recommended pattern for handling this? Using a interface{} or string for what should be an int field doesn’t seem ideal.
About this issue
- Original URL
- State: closed
- Created 7 years ago
- Comments: 22 (2 by maintainers)
Sorry for bumping this old and closed issue, but I’m running into the same problem here. I’m getting a
strconv.ParseInterror, which doesn’t tell me anything about which field failed validation (which is bad, because I want to show the users of my API which field was invalid).From @benmoss:
I think exactly that is a very good idea, and would go a long way towards solving this problem .
@appcypher you can change the type of
intfield tostringthennumberbinding will work as expected. You can convert the string to int afterwards. Here’s an exampleAlso running into this issue. This renders using the validator’s translator almost pointless because there is still a need to dissect what was invalid with the request when it was malformed in this specific way. We want to use translations to provide user-friendly messages for all input errors.
I too like the idea of standardising all of the errors coming out of the
Bindfunctions as much as possible toValidationErrors.@benmoss Could you please provide the code you’re trying to run? Probably the best rule for
Ageismin=10,max=0or you can simply usenumericwhich means you can use it like this:Gin uses http://godoc.org/gopkg.in/go-playground/validator.v8 as its validator. You can find the complete rules and documentation here: https://godoc.org/gopkg.in/go-playground/validator.v8
Please reopen this issue!
@benmoss Can this issue be reopened since this problem hasn’t been resolved? I will have to create a new one otherwise.
BTW, was anyone able to find a workaround for this? I would really hate to send cryptic error messages to my users.
@appleboy benmoss is right.
no, i will try to send a PR for this latter
please reopen, if a field defined as int, and client send a string like “abc”, it will comeout
strconv.ParseInt: parsing "abc": invalid syntax, not validation error@appleboy this solution still gives you a
json.UnmarshalTypeErrorrather than a validation error. What’s failing isjson.Unmarshal, and thenumericvalidation has no effect.@benmoss Have you tried what I told?
numericis the correct tag but you are usingnumber.