v10
validator treat json.Number as string
package main
import (
"encoding/json"
"fmt"
"github.com/go-playground/validator/v10"
)
type Test struct {
Val json.Number `validate:"min=20"`
}
func main() {
validate := validator.New()
test := Test{
Val: "100",
}
fmt.Println(validate.Struct(test))
}
Output:
Key: 'Test.Val' Error:Field validation for 'Val' failed on the 'min' tag
Expect:
No Error
I know json.Number is string,but if we define a type as json.Number,we prefer this value act as a number value, so is there any way to let validator behavior act as number too?
Hi @Tevic
Yes, I think there is a way to let the validator act as a numeric value for encoding/json.Number
I've implemented it in PR https://github.com/go-playground/validator/pull/634
I'm not very knowledgeable about this codebase yet, but as encoding/json.Number's underlying type is string, I think that creating a special case for string validations would make sense
Let's wait for maintainers to review it
Hey @Tevic @elias19r
As much as I'd like to merge that PR json.Number is in fact a string and not a number as so I'm hesitant to add this special case because:
Having said that, this sort of thing has been thought of and there are 3 options for dealing with this sort of thing from least to most recommended:
Please let me know if this helps :)
Most helpful comment
Hey @Tevic @elias19r
As much as I'd like to merge that PR
json.Numberis in fact a string and not a number as so I'm hesitant to add this special case because:Having said that, this sort of thing has been thought of and there are 3 options for dealing with this sort of thing from least to most recommended:
Please let me know if this helps :)