ValidateMapCtx does not support validating []map[string]interface{} in []interface #955

pull/956/head
leftjs 3 years ago
parent 9e2ea40380
commit 165e95e961
  1. 24
      validator_instance.go
  2. 10
      validator_test.go

@ -156,19 +156,29 @@ func (v Validate) ValidateMapCtx(ctx context.Context, data map[string]interface{
errs := make(map[string]interface{}) errs := make(map[string]interface{})
for field, rule := range rules { for field, rule := range rules {
if ruleObj, ok := rule.(map[string]interface{}); ok { 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) err := v.ValidateMapCtx(ctx, dataObj, ruleObj)
if len(err) > 0 { if len(err) > 0 {
errs[field] = err errs[field] = err
} }
} else if dataObjs, ok := data[field].([]map[string]interface{}); ok { }
for _, obj := range dataObjs { switch dataObj := data[field].(type) {
err := v.ValidateMapCtx(ctx, obj, ruleObj) case map[string]interface{}:
if len(err) > 0 { innerValidate(dataObj)
errs[field] = err 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") errs[field] = errors.New("The field: '" + field + "' is not a map to dive")
} }
} else if ruleStr, ok := rule.(string); ok { } else if ruleStr, ok := rule.(string); ok {

@ -12156,8 +12156,10 @@ func TestValidate_ValidateMapCtx(t *testing.T) {
"Test_D": "Test_D", "Test_D": "Test_D",
}, },
}, },
"Test_E": map[string]interface{}{ "Test_E": []interface{}{
"Test_F": "Test_F", map[string]interface{}{
"Test_F": "Test_F",
},
}, },
}, },
}, },
@ -12182,11 +12184,11 @@ func TestValidate_ValidateMapCtx(t *testing.T) {
data: map[string]interface{}{ data: map[string]interface{}{
"Test_A": map[string]interface{}{ "Test_A": map[string]interface{}{
"Test_B": "Test_B", "Test_B": "Test_B",
"Test_C": []interface{}{"Test_D"}, "Test_C": []interface{}{"is error"},
"Test_E": map[string]interface{}{ "Test_E": map[string]interface{}{
"Test_F": "Test_F", "Test_F": "Test_F",
}, },
"Test_G": "Test_G", "Test_G": "is error",
"Test_I": []map[string]interface{}{ "Test_I": []map[string]interface{}{
{ {
"Test_J": "Test_J", "Test_J": "Test_J",

Loading…
Cancel
Save