Skip to content

[Bug]: omitzero does not work with Slice #1424

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
AnalogJ opened this issue May 4, 2025 · 0 comments
Open

[Bug]: omitzero does not work with Slice #1424

AnalogJ opened this issue May 4, 2025 · 0 comments
Labels

Comments

@AnalogJ
Copy link

AnalogJ commented May 4, 2025

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
}
@AnalogJ AnalogJ added the bug label May 4, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant