Skip to content

Commit

Permalink
Align required_without with the contract stated in the documentation
Browse files Browse the repository at this point in the history
See this issue: go-playground#617
  • Loading branch information
jmfrees committed Oct 3, 2024
1 parent f1939ee commit 91f421e
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
7 changes: 5 additions & 2 deletions baked_in.go
Original file line number Diff line number Diff line change
Expand Up @@ -1979,8 +1979,11 @@ func excludedWithout(fl FieldLevel) bool {
// requiredWithout is the validation function
// The field under validation must be present and not empty only when any of the other specified fields are not present.
func requiredWithout(fl FieldLevel) bool {
if requireCheckFieldKind(fl, strings.TrimSpace(fl.Param()), true) {
return hasValue(fl)
params := parseOneOfParam2(fl.Param())
for _, param := range params {
if requireCheckFieldKind(fl, param, true) {
return hasValue(fl)
}
}
return true
}
Expand Down
26 changes: 26 additions & 0 deletions validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -11825,6 +11825,32 @@ func TestRequiredWithout(t *testing.T) {

errs = validate.Struct(&test3)
Equal(t, errs, nil)

test4 := struct {
Field1 string `validate:"required_without=Field2 Field3,omitempty,min=1" json:"field_1"`
Field2 string `json:"field_2"`
Field3 string `json:"field_3"`
}{
Field1: "test",
}

errs = validate.Struct(&test4)
Equal(t, errs, nil)

test5 := struct {
Field1 string `validate:"required_without=Field2 Field3,omitempty,min=1" json:"field_1"`
Field2 string `json:"field_2"`
Field3 string `json:"field_3"`
}{
Field3: "test",
}

errs = validate.Struct(&test5)
NotEqual(t, errs, nil)

ve = errs.(ValidationErrors)
Equal(t, len(ve), 1)
AssertError(t, errs, "Field1", "Field1", "Field1", "Field1", "required_without")
}

func TestRequiredWithoutAll(t *testing.T) {
Expand Down

0 comments on commit 91f421e

Please sign in to comment.