go-playground / validator

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

Required_if and required_unless not working as expected #1243

Closed MantasSilanskas closed 3 months ago

MantasSilanskas commented 3 months ago

Package version eg. v9, v10:

v10

Issue, Question or Enhancement:

required_if && required_unless not working as expected. I expect when nonExpiring is true that expiresAt field would be not required.

Code sample, to showcase or reproduce:

// JSONInputContractUpdate holds information used for contract update.
type JSONInputContractUpdate struct {
    ExpiresAt        time.Time           `json:"expiresAt" validate:"required_unless=nonExpiring true"`
....
    NonExpiring      bool                `json:"nonExpiring" validate:"omitempty"`

When I send

{
  "nonExpiring":false,
  "expiresAt":"2024-03-17T22:00:00.000Z",
... {other fields}
}

Everything is fine but when I do

{
  "nonExpiring":true,
... {other fields}
}

I get error - "Key: 'JSONInputContractCreate.ExpiresAt' Error:Field validation for 'ExpiresAt' failed on the 'required_unless' tag"

MantasSilanskas commented 3 months ago

Should have used struct name instead of json name aka -


// JSONInputContractUpdate holds information used for contract update.
type JSONInputContractUpdate struct {
    ExpiresAt        time.Time           `json:"expiresAt" validate:"required_unless=NonExpiring true"`
....
    NonExpiring      bool                `json:"nonExpiring" validate:"omitempty"```