As of v9, i don't see a way to validate a struct field that can only take values from a restricted set of possible values. This is meant to act as a replacement for sum types (enums).
Example use case: Making sure that User.Gender can take values within []string{"male", "female", "n/a"}
Any suggestions?
Hey @alexyans
there are 2 ways, I recommend the 2nd
validate:"eq=male|eq=female|eq=n/a"
Use a function eg.
const (
Val1 string = "value1"
Val2 string = "value2"
...
)
m := map[string]struct{}{
Val1:struct{}{},
Val2:struct{}{},
}
validate := validator.New()
validate.RegisterValidation("mytag", func(fl validator.FieldLevel) bool {
_,ok := m[fl.Field().String()]
return ok
})
please let me know if that makes sense.
Hi @joeybloggs Yes, this approach helped me. Thank you for your message. But, I found that we could do the validation without custom validation function. My suggestion is:
const (
Val1 string = "value1"
Val2 string = "value2"
...
)
m := map[string]struct{}{
Val1:struct{}{},
Val2:struct{}{},
}
_,ok := m[string]
if ok == true
return ok
There's a new validation added which could help.
Gender string `validator="oneof=male female n/a"`
I'm actually not sure if the slash will work, not sure if that's a reserved character. But may be useful anyway. Works with strings or whole numbers.
Most helpful comment
There's a new validation added which could help.
I'm actually not sure if the slash will work, not sure if that's a reserved character. But may be useful anyway. Works with strings or whole numbers.