-
Notifications
You must be signed in to change notification settings - Fork 124
Description
System (please complete the following information):
- OS:
linux - GO Version:
1.24.2 - Pkg Version:
v1.5.4
Describe the bug
When we try to validate a number in a request using validate.FromJSONBytes(), and we added a int rule for validation, the validation will not meet our expectation.
To Reproduce
- not use filter
func TestInt(t *testing.T) {
data := []byte(`{"value": 9223372036854775807}`)
dataFace, err := validate.FromJSONBytes(data)
if err != nil {
t.Error(err)
}
v := dataFace.Create()
v.StringRule("value", "int")
assert.Equal(t, v.Validate(), true)
}- use filter
func TestInt(t *testing.T) {
data := []byte(`{"value": 9223372036854775809}`)
dataFace, err := validate.FromJSONBytes(data)
if err != nil {
t.Error(err)
}
v := dataFace.Create()
v.FilterRule("value", "int64")
v.StringRule("value", "int")
assert.Equal(t, v.Validate(), true)
}Expected behavior
In the first case, 9223372036854775807 is within the int64 range, but the validate gives false. In the second case, 9223372036854775809 is not within the int64 range, but the validate gives true.
Additional context
We believe the reason for this is because the native json library will unmarshal the number into float64, and even if we filter it to int64, the number that validate library receives is not correct (see the screenshot). However, if we do not filter to int, it will always fail as the int validator only validates if a number is an int.
I am not sure about this, but I believe there are several possible solutions:
- we could use jsoniter instead of native json library, as the jsoniter offers the ability to unmarshal the number into json.Number (so that the number will not lose precision).
- I don't know if the int64 filter could throw out error if the number is out of range
Thank you very much, this is a fantastic library!