增加有条件必传的数据验证

This commit is contained in:
白茶清欢 2024-05-16 21:12:17 +08:00
parent 84d515bce2
commit 050fdcd504
2 changed files with 45 additions and 2 deletions

View File

@ -34,7 +34,8 @@ type FieldRule struct {
//
// Date : 10:58 2024/4/29
type RequiredCondition struct {
DependOnField string `json:"depend_on_field"` // 依赖数据园中的那一个字段
DependOnField string `json:"depend_on_field"` // 依赖数据源中的那一个字段
DependOnFieldType string `json:"depend_on_field_type"` // 依赖数据源数据类型
DependOnFieldStatus []string `json:"depend_on_field_status"` // 依赖数据状态 : NOT_FOUND / IS_NIL / IS_ZERO / IS_EMPTY / IS_FALSE
}

44
run.go
View File

@ -59,6 +59,8 @@ func Run(sourceData map[string]any, ruleList []*define.FieldRule) error {
// 未指定验证数据位置
continue
}
// 通过有条件必传, 填充 is_required
checkRuleConditionRequiredRule(byteData, itemRule)
inputFieldVal := gjson.GetBytes(byteData, itemRule.Path)
if formatRule, err := validate(byteData, inputFieldVal, itemRule); nil != err {
return err
@ -78,6 +80,32 @@ func Run(sourceData map[string]any, ruleList []*define.FieldRule) error {
return nil
}
// checkRuleConditionRequiredRule 校验有条件必传
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 21:10 2024/5/16
func checkRuleConditionRequiredRule(sourceData []byte, rule *define.FieldRule) {
if rule.IsRequired {
// 本身已经必传, 无所谓有条件无条件
return
}
// 验证有条件必传
if len(rule.RequiredConditionGroup) > 0 {
for _, itemRuleGroup := range rule.RequiredConditionGroup {
isRequired := true
for _, itemFieldRule := range itemRuleGroup {
dependFieldStatus := getDataStatus(gjson.GetBytes(sourceData, itemFieldRule.DependOnField), itemFieldRule.DependOnFieldType)
isRequired = isRequired && inArray(itemFieldRule.DependOnFieldStatus, dependFieldStatus)
}
if isRequired {
rule.IsRequired = true // 非必传参数, 命中有条件必传
break
}
}
}
}
// getDataStatus 获取数据状态
//
// Author : go_developer@163.com<白茶清欢>
@ -143,6 +171,20 @@ func formatInputVal(val gjson.Result, rule *define.FieldRule) (any, error) {
return inputVal, nil
}
// inArray ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 21:00 2024/5/16
func inArray(enumList []string, val string) bool {
for _, item := range enumList {
if strings.ToUpper(val) == strings.ToUpper(item) {
return true
}
}
return false
}
// validate 验证字段
//
// Author : go_developer@163.com<白茶清欢>
@ -153,11 +195,11 @@ func validate(sourceData []byte, val gjson.Result, rule *define.FieldRule) (any,
err error
inputVal any
)
if !val.Exists() {
if rule.IsRequired {
return nil, fmt.Errorf("%v : field is required, but not found", rule.Path)
}
// TODO : 验证有条件必传
inputVal = rule.DefaultValue
} else {
if inputVal, err = formatInputVal(val, rule); nil != err {