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 6c54727
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 3 deletions.
13 changes: 10 additions & 3 deletions baked_in.go
Original file line number Diff line number Diff line change
Expand Up @@ -1904,12 +1904,19 @@ func excludedUnless(fl FieldLevel) bool {
if len(params)%2 != 0 {
panic(fmt.Sprintf("Bad param number for excluded_unless %s", fl.FieldName()))
}
var canBeFilled bool
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) {
canBeFilled = true
break
}
}
return true

if canBeFilled {
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 6c54727

Please sign in to comment.