-
Notifications
You must be signed in to change notification settings - Fork 1.4k
Closed
Labels
Description
What happened?
omitzero should correctly ignore empty slices, instead validation continues.
Looks related to this switch case for hasZero - https://github.com/go-playground/validator/blob/master/baked_in.go#L1796
It incorrectly treats nil
as the zero case for slices.
Forked the code to experiment with that case, couldn't fix the issue. Looks like omitempty
is special in some way.
Version
v10.26.0
Example Code
omitempty
type MyType struct {
//OrgId string `validate:"required"`
MySlice []string `validate:"omitempty,min=1,dive,uri"`
}
func (req *MyType) Validate() error {
validate := validator.New(validator.WithRequiredStructEnabled())
return validate.Struct(req)
}
func main() {
myInstance1 := &MyType{
MySlice: nil,
}
log.Printf("isValid: %v", myInstance1.Validate())
// isValid: <nil>
myInstance2 := &MyType{
MySlice: []string{},
}
log.Printf("isValid: %v", myInstance2.Validate())
// isValid: Key: 'MyType.MySlice' Error:Field validation for 'MySlice' failed on the 'min' tag
}
omitzero -- which should handle empty slice correctly
type MyType struct {
//OrgId string `validate:"required"`
MySlice []string `validate:"omitzero,min=1,dive,uri"`
}
func (req *MyType) Validate() error {
validate := validator.New(validator.WithRequiredStructEnabled())
return validate.Struct(req)
}
func main() {
myInstance1 := &MyType{
MySlice: nil,
}
log.Printf("isValid: %v", myInstance1.Validate())
//isValid: <nil>
myInstance2 := &MyType{
MySlice: []string{},
}
log.Printf("isValid: %v", myInstance2.Validate())
//isValid: Key: 'MyType.MySlice' Error:Field validation for 'MySlice' failed on the 'min' tag
}