Skip to content

Commit

Permalink
allows multiple values of same field on excluded_uunless to have oppo…
Browse files Browse the repository at this point in the history
…site equivilant result to required_unless
  • Loading branch information
chargraves85 committed Aug 16, 2024
1 parent a947377 commit ca3636f
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 3 deletions.
7 changes: 4 additions & 3 deletions baked_in.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
38 changes: 38 additions & 0 deletions validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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) {
Expand Down

0 comments on commit ca3636f

Please sign in to comment.