From ca3636f415b629f6186823552703f228cc2be254 Mon Sep 17 00:00:00 2001 From: Chris Hargraves Date: Fri, 16 Aug 2024 14:07:47 -0400 Subject: [PATCH] allows multiple values of same field on excluded_uunless to have opposite equivilant result to required_unless --- baked_in.go | 7 ++++--- validator_test.go | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/baked_in.go b/baked_in.go index b6fbaafa..3e98a2ec 100644 --- a/baked_in.go +++ b/baked_in.go @@ -1905,11 +1905,12 @@ func excludedUnless(fl FieldLevel) bool { panic(fmt.Sprintf("Bad param number for excluded_unless %s", fl.FieldName())) } for i := 0; i < len(params); i += 2 { - if !requireCheckFieldValue(fl, params[i], params[i+1], false) { - return !hasValue(fl) + if requireCheckFieldValue(fl, params[i], params[i+1], false) { + return true } } - return true + + return !hasValue(fl) } // excludedWith is the validation function diff --git a/validator_test.go b/validator_test.go index 0f96b777..bd7ee481 100644 --- a/validator_test.go +++ b/validator_test.go @@ -11140,6 +11140,24 @@ func TestRequiredUnless(t *testing.T) { Inner: &Inner{Field: &fieldVal}, } _ = validate.Struct(test3) + + test4 := struct { + Field1 int + Field2 string `validate:"required_unless: Field1 1 Field1 2"` + Field3 int + Field4 string `validate:"required_unless: Field3 1 Field3 2"` + }{ + Field1: 1, + Field3: 3, + } + + errs = validate.Struct(test4) + NotEqual(t, errs, nil) + + ve = errs.(ValidationErrors) + Equal(t, len(ve), 1) + + AssertError(t, errs, "Field2", "Field2", "Field2", "Field2", "required_unless") } func TestSkipUnless(t *testing.T) { @@ -12126,6 +12144,26 @@ func TestExcludedUnless(t *testing.T) { Inner: &Inner{Field: &fieldVal}, } _ = validate.Struct(panicTest) + + test9 := struct { + Field1 int + Field2 string `validate:"excluded_unless: Field1 1 Field1 2"` + Field3 int + Field4 string `validate:"excluded_unless: Field3 1 Field3 2"` + }{ + Field1: 1, + Field2: "foo", + Field3: 3, + Field4: "foo", + } + + errs = validate.Struct(test9) + NotEqual(t, errs, nil) + + ve = errs.(ValidationErrors) + Equal(t, len(ve), 1) + + AssertError(t, errs, "Field2", "Field2", "Field2", "Field2", "required_unless") } func TestLookup(t *testing.T) {