From e3e24a10a9f4198b520e80e645cab9ea0d9cafce Mon Sep 17 00:00:00 2001 From: hzy Date: Mon, 3 Jul 2023 17:04:05 +0800 Subject: [PATCH] struct can be null flag --- validator_instance.go | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/validator_instance.go b/validator_instance.go index ccf4aa6..29e4979 100644 --- a/validator_instance.go +++ b/validator_instance.go @@ -150,14 +150,14 @@ func (v *Validate) SetTagName(name string) { v.tagName = name } -const omitemptyStructPrefix = "__omitempty_struct__" +const omitemptyPrefix = "__omitempty__" // ValidateMapCtx validates a map using a map of validation rules and allows passing of contextual // validation validation information via context.Context. func (v Validate) ValidateMapCtx(ctx context.Context, data map[string]interface{}, rules map[string]interface{}) map[string]interface{} { errs := make(map[string]interface{}) for field, rule := range rules { - if strings.HasPrefix(field, omitemptyStructPrefix) == true { + if strings.HasPrefix(field, omitemptyPrefix) == true { continue } if ruleObj, ok := rule.(map[string]interface{}); ok { @@ -170,20 +170,27 @@ func (v Validate) ValidateMapCtx(ctx context.Context, data map[string]interface{ } else { errs[field] = errors.New("The field: '" + field + "' is not a map to dive") } - } else if _, ok := rules[fmt.Sprintf("%s%s", omitemptyStructPrefix, field)].(string); ok { - // struct can be null + } else if _, ok := rules[fmt.Sprintf("%s%s", omitemptyPrefix, field)].(string); ok { + // can be null continue } else { errs[field] = errors.New("The field: '" + field + "' is not a map to dive") } } else if arrRuleObj, ok := rule.([]map[string]interface{}); ok { - if dataObjs, ok := data[field].([]map[string]interface{}); ok && len(arrRuleObj) > 0 { - for _, obj := range dataObjs { - err := v.ValidateMapCtx(ctx, obj, arrRuleObj[0]) - if len(err) > 0 { - errs[field] = err + if dataObjs, ok := data[field]; ok { + if do, ok := dataObjs.([]map[string]interface{}); ok && len(arrRuleObj) > 0 { + for _, obj := range do { + err := v.ValidateMapCtx(ctx, obj, arrRuleObj[0]) + if len(err) > 0 { + errs[field] = err + } } + } else { + errs[field] = errors.New("The field: '" + field + "' is not a map array") } + } else if _, ok := rules[fmt.Sprintf("%s%s", omitemptyPrefix, field)].(string); ok { + // can be null + continue } else { errs[field] = errors.New("The field: '" + field + "' is not a map array") }