Validator: Membership validation

Created on 2 Oct 2017  路  3Comments  路  Source: go-playground/validator

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?

question

Most helpful comment

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.

All 3 comments

Hey @alexyans

there are 2 ways, I recommend the 2nd

  1. validate:"eq=male|eq=female|eq=n/a"

  2. 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.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

thaonx picture thaonx  路  3Comments

timakin picture timakin  路  3Comments

Jake-Convictional picture Jake-Convictional  路  4Comments

phenrigomes picture phenrigomes  路  5Comments

deschmih picture deschmih  路  3Comments