validator icon indicating copy to clipboard operation
validator copied to clipboard

need tag like `skip_unless`

Open yinghao-liu opened this issue 3 years ago • 1 comments

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

Package version eg. v9, v10:

v10.4.1

Issue, Question or Enhancement:

Enhancement

Code sample, to showcase or reproduce:

type TV struct {
	Size string `validate:"oneof=big small"`
}
type Fan struct {
	Speed string `validate:"oneof=fast slow"`
}

type Suite struct {
	SuiteType string `validate:"oneof=tv fan"`
	TV        TV
	Fan       Fan
}

func TestSuite(t *testing.T) {
	var s Suite
	s.SuiteType = "tv"
	s.TV.Size = "big"

	Validate(s)
}

I got an error: Key: 'Suite.Fan.Speed' Error:Field validation for 'Speed' failed on the 'oneof' tag

what I want:
I need a tag something like skip_unless,after that, there is no error
because I do not care what the Fan are

type Suite struct {
	SuiteType string `validate:"oneof=tv fan"`
	TV        TV `validate:"skip_unless=SuiteType tv"`
	Fan       Fan `validate:"skip_unless=SuiteType fan"`
}

if there is other way, thanks!!!

yinghao-liu avatar Mar 02 '22 09:03 yinghao-liu

@yinghao-liu Following is the possible work around to the problem you faced :

type TV struct {
	Size string `validate:"oneof=big small"`
}

type Fan struct {
	Speed string `validate:"oneof=fast slow"`
}

type Suite struct {
	SuiteType string `validate:"oneof=tv fan"`
	TV        *TV    `validate:"required_unless=SuiteType fan"`
	Fan       *Fan   `validate:"required_unless=SuiteType tv"`
}

func main() {
	tv := Suite{
		SuiteType: "tv",
		TV: &TV{
			Size: "big",
		},
	}

	v := validator.New()
	fmt.Println(v.StructCtx(context.Background(), tv))

	fan := Suite{
		SuiteType: "fan",
		Fan: &Fan{
			Speed: "fast",
		},
	}

	fmt.Println(v.StructCtx(context.Background(), fan))
}

Let me know, if you have any query. Thanks!

JahanviAggarwal avatar May 08 '22 17:05 JahanviAggarwal