As @mkopriva points out, you can use the dive
keyword to check the elements of a slice.
To offer more explanation:
- some rules, like
min
are overloaded and apply to both scalar and slice types
- other rules, like
oneof
apply only to scalars; (in the example below, a call to validate.Struct
causes a panic when the struct has a oneof
rule directly on a slice)
dive
pushes rules like oneof
down to the elements of a slice. (the example also shows min
, dive
, and oneof
working together without panicking).
type (
demoA struct {
Values []string `validate:"oneof=VALUE1 VALUE2 VALUE3"`
}
demoB struct {
Values []string `validate:"min=1"`
}
demoC struct {
Values []string `validate:"min=1,dive,oneof=VALUE1 VALUE2 VALUE3"`
}
)
var validate = validator.New()
func main() {
safeValidate(demoA{[]string{}})
fmt.Println()
doValidate(demoB{[]string{}})
doValidate(demoB{[]string{"foo"}})
fmt.Println()
doValidate(demoC{[]string{}})
doValidate(demoC{[]string{"foo"}})
doValidate(demoC{[]string{"VALUE2"}})
fmt.Println()
}