go-playground / validator

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

Add optional or nullable rules - useful for ValidateMap #1092

Closed arxeiss closed 1 year ago

arxeiss commented 1 year ago

Package version eg. v9, v10:

v10

Issue, Question or Enhancement:

When using ValidateMap I would like to set some entries as optional. So if it is not set or set to nil, none of the rules then is applied. Because now when I have a rule for map entry, which does not exist in data map, I got an error.

Code sample, to showcase or reproduce:

// this returns an errors:
// - plan is required field <- this is OK
// - car must be one of volvo bmw <- this is not OK
res = v.ValidateMap(
    map[string]interface{}{},
    map[string]interface{}{
        "plan": "required,oneof=gold silver bronze",
        "car":  "oneof=volvo bmw",
    },
)

// would be nice to support something like this
// this would return ONLY 1 error:
// - plan is required field
// - car is optional, so no more validation happen
// - phone is optional, so no more validation happen even it is `nil`
res = v.ValidateMap(
    map[string]interface{}{
        "phone": nil
    },
    map[string]interface{}{
        "plan":  "required,oneof=gold silver bronze",
        "car":   "optional,oneof=volvo bmw",
        "phone": "optional,oneof=iPhone Android Other",
    },
)
zemzale commented 1 year ago

You are looking for omitempty https://pkg.go.dev/github.com/go-playground/validator/v10#hdr-Omit_Empty

arxeiss commented 1 year ago

Sorry, I was searching nullable and optional and totally missed that one