Skip to content

The int validator failed to validate a number exceeds the range of int64 #316

@Jerry20000730

Description

@Jerry20000730

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

  1. 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)
}
  1. 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.

Image

I am not sure about this, but I believe there are several possible solutions:

  1. 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).
  2. 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!

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions