Skip to content

Commit

Permalink
Merge pull request #27 from Rhyanz46/avoidnullfield
Browse files Browse the repository at this point in the history
fixing bugs on `requiredWithout`
  • Loading branch information
Rhyanz46 authored Mar 9, 2024
2 parents 31b0ec1 + fe637ee commit 9aa629b
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 2 deletions.
8 changes: 6 additions & 2 deletions map_validator/functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,15 +164,19 @@ func validateRecursive(wrapper *RulesWrapper, key string, data map[string]interf

if endOfLoop && wrapper.requiredWithout != nil {
for _, field := range *wrapper.nullFields {
var required bool
dependenciesField := (*wrapper.requiredWithout)[field]
if len(dependenciesField) == 0 {
continue
}
for _, XField := range dependenciesField {
if isDataInList(XField, *wrapper.nullFields) {
return nil, errors.New(fmt.Sprintf("if field '%s' is null you need to put value in this %v field", field, dependenciesField))
if isDataInList(XField, *wrapper.filledField) {
required = true
}
}
if !required {
return nil, errors.New(fmt.Sprintf("if field '%s' is null you need to put value in this %v field", field, dependenciesField))
}
}
}

Expand Down
32 changes: 32 additions & 0 deletions test/required_without_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -59,3 +59,35 @@ func TestChildRequiredWithout(t *testing.T) {
t.Errorf("Expected error with text at least %s, but we got %s", expected, err)
}
}

func TestClearChildRequiredWithout(t *testing.T) {
role := map_validator.RulesWrapper{
Rules: map[string]map_validator.Rules{
"data": {Object: &map_validator.RulesWrapper{
Rules: map[string]map_validator.Rules{
"name": {Type: reflect.String},
"expired": {Type: reflect.String, Null: true},
"flavor": {Type: reflect.String, RequiredWithout: []string{"custom_flavor", "size"}},
"custom_flavor": {Type: reflect.String, RequiredWithout: []string{"flavor", "size"}},
"size": {Type: reflect.Int, RequiredWithout: []string{"flavor", "custom_flavor"}},
},
}},
},
}
payload := map[string]interface{}{
"data": map[string]interface{}{
"name": "sabalong",
"size": 63,
},
}
check, err := map_validator.NewValidateBuilder().SetRules(role).Load(payload)
if err != nil {
t.Errorf("Expected not have error, but got error : %s", err)
return
}
_, err = check.RunValidate()
if err != nil {
t.Errorf("Expected not have error, but got error : %s", err)
return
}
}

0 comments on commit 9aa629b

Please sign in to comment.