go-playground / validator

:100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving
MIT License
16.53k stars 1.31k forks source link

Question: Range/Bounds validation #1053

Closed vasu-dasari closed 1 year ago

vasu-dasari commented 1 year ago

Wondering if there is a way to check range for an integer value on a slice of integers.

For example in this following call,

errs = v.Var(131, "gte=0,lte=130") validation is performed successfully. The function returns error appropriately, "Error:Field validation for '' failed on the 'lte' tag"

How can I perform such a validation a slice of integers without writing my own custom validator. I see there is an option, "dive" for slices/maps. Can the "dive" be extended to get what I am requesting?

var tag := "what should go here?"
err := validate.Var([]int{1, 2, 3, 4, 5, 6}, tag)

In summary, I am looking for "tag" that should be employed above to validate, list of integers to be within the range of 1-5. In above example such validation would fail, as last element 6 is greater than 5.

ashwek commented 1 year ago

@vasu-dasari You can try something like this

err := validate.Var([]int{1, 2, 3, 4, 5, 6}, "dive,min=1,max=5")
if err != nil {
    fmt.Println("error validating", err)
    return
}
vasu-dasari commented 1 year ago

@ashwek Thank you for the suggestion for numeric slices.

Is there a validation available for numeric-arrays? Say for example validation should raise an error if value is greater than 5.

var tag := "what should go here?"
err := validate.Var("1,2,3,4,5,6,7", tag)
zemzale commented 1 year ago
tag := "dive,gt=0,lte=5"
err := validate.Var([]int{1, 2, 3, 4, 5, 6}, tag)

This will work for that. Dive tag runs validation on each element in the slice that comes after it. So in this case it would run gt=0 and let=5 on each element in the slice.

See: https://pkg.go.dev/github.com/go-playground/validator/v10#hdr-Dive If you have any other questions feel free to leave them, but I am closing this issue.