Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add the ability to validate a slice of submaps to validate map #859

Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
9 changes: 9 additions & 0 deletions validator_instance.go
Expand Up @@ -5,6 +5,7 @@ import (
"errors"
"fmt"
"reflect"
"strconv"
"strings"
"sync"
"time"
Expand Down Expand Up @@ -157,6 +158,14 @@ func (v Validate) ValidateMapCtx(ctx context.Context, data map[string]interface{
if len(err) > 0 {
errs[field] = err
}
} else if reflect.ValueOf(rule).Kind() == reflect.Map && reflect.ValueOf(data[field]).Kind() == reflect.Slice {
for i := 0; i < reflect.ValueOf(data[field]).Len(); i++ {
fieldWithIndex := field + "[" + strconv.FormatInt(int64(i), 10) + "]"
err := v.ValidateMapCtx(ctx, reflect.ValueOf(data[field]).Index(i).Interface().(map[string]interface{}), rule.(map[string]interface{}))
if len(err) > 0 {
errs[fieldWithIndex] = err
}
}
} else if reflect.ValueOf(rule).Kind() == reflect.Map {
errs[field] = errors.New("The field: '" + field + "' is not a map to dive")
} else {
Expand Down
47 changes: 47 additions & 0 deletions validator_test.go
Expand Up @@ -11418,3 +11418,50 @@ func TestPostCodeByIso3166Alpha2Field_InvalidKind(t *testing.T) {
_ = New().Struct(test{"ABC", 123, false})
t.Errorf("Didn't panic as expected")
}

func TestValidate_ValidateMap_WithSlicesOfStructs(t *testing.T) {
test := map[string]interface{}{
"value": []map[string]interface{}{
{
"subValue": "abc",
}, {},
},
}
rules := map[string]interface{}{
"value": map[string]interface{}{
"subValue": "required",
},
}
errs := New().ValidateMap(test, rules)
NotEqual(t, nil, errs)
}

func TestValidate_ValidateMap_WithSubMaps(t *testing.T) {
test := map[string]interface{}{
"value": map[string]interface{}{
"subValue": "abc",
},
}
rules := map[string]interface{}{
"value": map[string]interface{}{
"subValue": "required",
},
}
errs := New().ValidateMap(test, rules)
NotEqual(t, nil, errs)
}

func TestValidate_ValidateMap_InvalidType(t *testing.T) {
test := map[string]interface{}{
"value": "abc",
}
rules := map[string]interface{}{
"value": map[string]interface{}{
"subValue": "required",
},
}
errs := New().ValidateMap(test, rules)
if IsEqual(errs, nil) {
t.Fatal("expected field error")
}
}