From 165e95e961ba4e67a09fad68d06625c3e7188e85 Mon Sep 17 00:00:00 2001 From: leftjs Date: Thu, 2 Jun 2022 14:30:43 +0800 Subject: [PATCH] ValidateMapCtx does not support validating []map[string]interface{} in []interface #955 --- validator_instance.go | 24 +++++++++++++++++------- validator_test.go | 10 ++++++---- 2 files changed, 23 insertions(+), 11 deletions(-) diff --git a/validator_instance.go b/validator_instance.go index 9493da4..a75ca7b 100644 --- a/validator_instance.go +++ b/validator_instance.go @@ -156,19 +156,29 @@ func (v Validate) ValidateMapCtx(ctx context.Context, data map[string]interface{ errs := make(map[string]interface{}) for field, rule := range rules { if ruleObj, ok := rule.(map[string]interface{}); ok { - if dataObj, ok := data[field].(map[string]interface{}); ok { + + innerValidate := func(dataObj map[string]interface{}) { err := v.ValidateMapCtx(ctx, dataObj, ruleObj) if len(err) > 0 { errs[field] = err } - } else if dataObjs, ok := data[field].([]map[string]interface{}); ok { - for _, obj := range dataObjs { - err := v.ValidateMapCtx(ctx, obj, ruleObj) - if len(err) > 0 { - errs[field] = err + } + switch dataObj := data[field].(type) { + case map[string]interface{}: + innerValidate(dataObj) + case []map[string]interface{}: + for _, obj := range dataObj { + innerValidate(obj) + } + case []interface{}: // json.Unmarshal() will convert JSON Array to []interface + for _, obj := range dataObj { + if mapObj, ok := obj.(map[string]interface{}); ok { + innerValidate(mapObj) + } else { + errs[field] = errors.New("The field: '" + field + "' is not a map to dive") } } - } else { + default: errs[field] = errors.New("The field: '" + field + "' is not a map to dive") } } else if ruleStr, ok := rule.(string); ok { diff --git a/validator_test.go b/validator_test.go index 1ebdea5..b977395 100644 --- a/validator_test.go +++ b/validator_test.go @@ -12156,8 +12156,10 @@ func TestValidate_ValidateMapCtx(t *testing.T) { "Test_D": "Test_D", }, }, - "Test_E": map[string]interface{}{ - "Test_F": "Test_F", + "Test_E": []interface{}{ + map[string]interface{}{ + "Test_F": "Test_F", + }, }, }, }, @@ -12182,11 +12184,11 @@ func TestValidate_ValidateMapCtx(t *testing.T) { data: map[string]interface{}{ "Test_A": map[string]interface{}{ "Test_B": "Test_B", - "Test_C": []interface{}{"Test_D"}, + "Test_C": []interface{}{"is error"}, "Test_E": map[string]interface{}{ "Test_F": "Test_F", }, - "Test_G": "Test_G", + "Test_G": "is error", "Test_I": []map[string]interface{}{ { "Test_J": "Test_J",