Search code examples
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:

    • some rules, like min are overloaded and apply to both scalar and slice types
    • other rules, like oneof apply only to scalars; (in the example below, a call to validate.Struct causes a panic when the struct has a oneof rule directly on a slice)
    • dive pushes rules like oneof down to the elements of a slice. (the example also shows min, dive, and oneof working together without panicking).
    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()
    }