diff --git a/util/validate_v10_parse.go b/util/validate_v10_parse.go index 11f79de..852acab 100644 --- a/util/validate_v10_parse.go +++ b/util/validate_v10_parse.go @@ -10,12 +10,89 @@ package util import ( "reflect" "strings" + + "git.zhangdeman.cn/zhangdeman/consts" + utilPkg "git.zhangdeman.cn/zhangdeman/util" ) // ParseValidateRule 解析验证规则 -func ParseValidateRule(dataType reflect.Kind, ruleStr string) map[string]any { +func ParseValidateRule(dataType reflect.Type, ruleStr string) ValidateRule { + if dataType.Kind() == reflect.Ptr { + dataType = dataType.Elem() + } + dataKind := dataType.Kind() + rule := ValidateRule{ + Omitempty: false, + Required: false, + Lte: nil, + Gte: nil, + Lt: nil, + Gt: nil, + Len: nil, + Max: nil, + Min: nil, + Eq: nil, + Ne: nil, + Oneof: nil, + } ruleList := strings.Split(ruleStr, ",") - return nil + for _, itemRule := range ruleList { + itemRule = strings.ToLower(strings.TrimSpace(itemRule)) + if len(itemRule) == 0 { + continue + } + if strings.Contains(itemRule, "=") { + // 一定是无需要值的验证规则 + switch itemRule { + case consts.ValidatorRuleCommonRequired.String(): // 必传 + rule.Required = true + case consts.ValidatorRuleCommonOmitempty.String(): // 为空则不校验 + rule.Omitempty = true + } + continue + } + itemRuleArr := strings.Split(itemRule, "=") + ruleType := itemRuleArr[0] + ruleValue := strings.Join(itemRuleArr[1:], "=") + if len(ruleValue) == 0 { + // 未配置值的校验规则 + continue + } + switch ruleType { + case consts.ValidateRuleLte.String(), consts.ValidateRuleGte.String(), consts.ValidateRuleGt.String(), consts.ValidateRuleLt.String(): // 数字取值范围 + var val float64 + if err := utilPkg.ConvertAssign(&val, ruleValue); nil == err { + switch ruleType { + case consts.ValidateRuleLte.String(): + rule.Lte = &val + case consts.ValidateRuleGte.String(): + rule.Gte = &val + case consts.ValidateRuleGt.String(): + rule.Gt = &val + case consts.ValidateRuleLt.String(): + rule.Lt = &val + } + } + case consts.ValidatorRuleCommonLen.String(), consts.ValidatorRuleCommonMin.String(), consts.ValidatorRuleCommonMax.String(): // 长度取值范围 + var val uint + if err := utilPkg.ConvertAssign(&val, ruleValue); nil == err { + switch ruleType { + case consts.ValidatorRuleCommonLen.String(): + rule.Len = &val + case consts.ValidatorRuleCommonMin.String(): + rule.Min = &val + case consts.ValidatorRuleCommonMax.String(): + rule.Max = &val + } + } + case consts.ValidateRuleEq.String(): + rule.Eq = ruleValue + case consts.ValidateRuleNe.String(): + rule.Ne = ruleValue + case consts.ValidatorRuleCommonOneOf.String(): + } + } + return rule } type ValidateRule struct {