go-playground / validator

:100:Go Struct and Field validation, including Cross Field, Cross Struct, Map, Slice and Array diving
MIT License
16.83k stars 1.32k forks source link

new tag oneof / containsonly for slice of string validation of allowed values #1006

Closed modest0 closed 2 years ago

modest0 commented 2 years ago

Package version eg. v9, v10:

v10

Issue, Question or Enhancement:

Question

Code sample, to showcase or reproduce:

I have a common scenario here where I need to validate if all the values received in a slice of string are contained / exists in a known set of allowed values. I always end up writting a custom validator but I wonder if it's possible achieve the same thing with the built in rules or a new set of rules like a containsOnly or anyOf.


type Request struct {
    PaymentOptions []string `json:"paymentOptions" validate:"required,anyof=visa amex cash voucher'"` // illustration purposes
}

allowedValues := []string{"visa", "amex", "cash", "voucher"}

r := Request{
    PaymentOption: []string{"cash", "invalid-option"}
}

validator.Struct(r) // should return an error stating that "invalid-option" is not a valid value
zemzale commented 2 years ago

@modest0 You certainly can do this, by using the dive tag. Example would be

type Request struct {
    PaymentOptions []string `json:"paymentOptions" validate:"required,dive,oneof=visa amex cash voucher'"`
}

See: https://go.dev/play/p/31TZwJBGGjx https://pkg.go.dev/github.com/go-playground/validator/v10#hdr-Dive