validator
validator copied to clipboard
need tag like `skip_unless`
- [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 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!