govalidationgo-playground

How can I validate an array of strings from a JSON in Golang with validator package?


I'm using the package validator to help me deal with JSON fields in golang. I know how to use oneof to check for specific values in a field. Is there any option for doing the same, but for an array of strings?

I'm trying to do something like this:

type ResponseEntity struct {
    Values       []string  `json:"values" validate:"oneof=VALUE1 VALUE2 VALUE3"`
}

Solution

  • As @mkopriva points out, you can use the dive keyword to check the elements of a slice.

    To offer more explanation:

    type (
        demoA struct {
            Values []string `validate:"oneof=VALUE1 VALUE2 VALUE3"`
        }
        demoB struct {
            Values []string `validate:"min=1"`
        }
        demoC struct {
            Values []string `validate:"min=1,dive,oneof=VALUE1 VALUE2 VALUE3"`
        }
    )
    
    var validate = validator.New()
    
    func main() {
        safeValidate(demoA{[]string{}})
        fmt.Println()
    
        doValidate(demoB{[]string{}})
        doValidate(demoB{[]string{"foo"}})
        fmt.Println()
    
        doValidate(demoC{[]string{}})
        doValidate(demoC{[]string{"foo"}})
        doValidate(demoC{[]string{"VALUE2"}})
        fmt.Println()
    }