Skip to content
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

Additional validation tags unnecessarily executed for fields that do not fulfill required_with condition #1340

Open
2 tasks done
llugin opened this issue Dec 6, 2024 · 1 comment
Labels

Comments

@llugin
Copy link

llugin commented Dec 6, 2024

  • I have looked at the documentation here first?
  • I have looked at the examples provided that may showcase my question here?

Package version eg. v9, v10:

v10 v10.23.0

Issue, Question or Enhancement:

When I have additional validation tag (file in my case) added to the field with tag required_with and the required_with condition is not fulfilled, then I expect that any additional validation will not be run as the field is legally not set. Instead, the additional file validation is still being run on unset field and fails. I tried using | as suggested in #570 , but that doesn't work either - in this case it seems like after fulfilling required_with conditions, the additional validation is not run at all.

Code sample, to showcase or reproduce:

package main

import (
	"fmt"

	"github.com/go-playground/validator/v10"
)

type Config struct {
	Field1 string `validate:"required_with=Field2,file"`
	Field2 string `validate:"required_with=Field1,file"`
}

type ConfigOr struct {
	Field1 string `validate:"required_with=Field2|file"`
	Field2 string `validate:"required_with=Field1|file"`
}

func main() {
	validate := validator.New(validator.WithRequiredStructEnabled())

	confEmpty := Config{}
	err := validate.Struct(confEmpty)
	if err != nil {
		fmt.Println("confEmpty", err)
	} else {
		fmt.Println("confEmpty validation success")
	}

	confOR := ConfigOr{
		Field1: "file1",
		Field2: "file-not-exist", // should fail
	}
	err = validate.Struct(confOR)
	if err != nil {
		fmt.Println("confOr", err)
	} else {
		fmt.Println("confOr validation success")
	}
}
confEmpty error: Key: 'Config.Field1' Error:Field validation for 'Field1' failed on the 'file' tag
Key: 'Config.Field2' Error:Field validation for 'Field2' failed on the 'file' tag
confOr validation success
@zemzale
Copy link
Member

zemzale commented Dec 10, 2024

type Config struct {
	Field1 string `validate:"required_with=Field2,omitempty,file"`
	Field2 string `validate:"required_with=Field1,omitempty,file"`
}

This should fix your issue. If the first validation didn't do anything, it can just skip anything afterward. Please close the issue if this fixes your problem.

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

2 participants