Skip to content

Commit

Permalink
validator: ValidateMap: make sure that required fields exist
Browse files Browse the repository at this point in the history
  • Loading branch information
mie00 committed May 10, 2019
1 parent 5930b28 commit 9abeb39
Show file tree
Hide file tree
Showing 2 changed files with 66 additions and 1 deletion.
21 changes: 20 additions & 1 deletion validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -809,10 +809,29 @@ func ValidateMap(s map[string]interface{}, m map[string]interface{}) (bool, erro
result = result && presentResult && typeResult && resultField && structResult && mapResult
index++
}
// check required keys
requiredResult := true
for key, value := range m {
if schema, ok := value.(string); ok {
tags := parseTagIntoMap(schema)
if required, ok := tags["required"]; ok {
if _, ok := s[key]; !ok {
requiredResult = false
if required.customErrorMessage != "" {
err = Error{key, fmt.Errorf(required.customErrorMessage), true, "required", []string{}}
} else {
err = Error{key, fmt.Errorf("required field missing"), false, "required", []string{}}
}
errs = append(errs, err)
}
}
}
}

if len(errs) > 0 {
err = errs
}
return result, err
return result && requiredResult, err
}

// ValidateStruct use tags for fields.
Expand Down
46 changes: 46 additions & 0 deletions validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3904,6 +3904,52 @@ func TestValidateMap(t *testing.T) {
}
}

func TestValidateMapMissing(t *testing.T) {
t.Parallel()
var tests = []struct {
params map[string]interface{}
validator map[string]interface{}
expected bool
}{
{
map[string]interface{}{
"name": "Bob",
},
map[string]interface{}{
"name": "required,alpha",
"family": "required,alpha",
},
false,
},
{
map[string]interface{}{
"name": "Bob",
"submap": map[string]interface{}{
"family": "Smith",
},
},
map[string]interface{}{
"name": "required,alpha",
"submap": map[string]interface{}{
"name": "required,alpha",
"family": "required,alpha",
},
},
false,
},
}

for _, test := range tests {
actual, err := ValidateMap(test.params, test.validator)
if actual != test.expected {
t.Errorf("Expected ValidateMap(%q, %q) to be %v, got %v", test.params, test.validator, test.expected, actual)
if err != nil {
t.Errorf("Got Error on ValidateMap(%q, %q): %s", test.params, test.validator, err)
}
}
}
}

func TestIsType(t *testing.T) {
t.Parallel()
i := 1
Expand Down

0 comments on commit 9abeb39

Please sign in to comment.