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

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

@ -156,21 +156,31 @@ 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")
}
}
default:
errs[field] = errors.New("The field: '" + field + "' is not a map to dive")
}
} else if ruleStr, ok := rule.(string); ok {
err := v.VarCtx(ctx, data[field], ruleStr)
if err != nil {

@ -12156,11 +12156,13 @@ func TestValidate_ValidateMapCtx(t *testing.T) {
"Test_D": "Test_D",
},
},
"Test_E": map[string]interface{}{
"Test_E": []interface{}{
map[string]interface{}{
"Test_F": "Test_F",
},
},
},
},
rules: map[string]interface{}{
"Test_A": map[string]interface{}{
"Test_B": "min=2",
@ -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",

Loading…
Cancel
Save