支持动态生成结构体并验证
This commit is contained in:
@ -9,6 +9,7 @@ package v10
|
||||
|
||||
import (
|
||||
"git.zhangdeman.cn/gateway/validator/v10/define"
|
||||
"git.zhangdeman.cn/zhangdeman/wrapper"
|
||||
"sync"
|
||||
)
|
||||
|
||||
@ -63,3 +64,27 @@ func ValidateMap(inputMap map[string]any, ruleConfigMap map[string]define.FieldV
|
||||
wg.Wait()
|
||||
return errTable
|
||||
}
|
||||
|
||||
// ValidateDynamicStruct 验证动态结构体
|
||||
//
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 17:28 2025/1/24
|
||||
func ValidateDynamicStruct(inputMap map[string]any, ruleConfigMap map[string]define.FieldValidateGenerateConfig) error {
|
||||
realMapData := make(map[string]any)
|
||||
tagMap := make(map[string]string)
|
||||
for mapKey, mapVal := range inputMap {
|
||||
if _, exist := ruleConfigMap[mapKey]; !exist {
|
||||
continue
|
||||
}
|
||||
realMapData[mapKey] = mapVal
|
||||
express, err := fieldValidatorRuleExpressGenerateFunc(ruleConfigMap[mapKey])
|
||||
if nil != err {
|
||||
return err
|
||||
}
|
||||
tagMap[mapKey] = "validate:\"" + express + "\""
|
||||
}
|
||||
dynamicStruct := wrapper.NewMap2DynamicStruct(realMapData, tagMap)
|
||||
structVal := dynamicStruct.ToStructDefaultValue()
|
||||
return validateInstance.Struct(structVal)
|
||||
}
|
||||
|
39
v10/validate_value_test.go
Normal file
39
v10/validate_value_test.go
Normal file
@ -0,0 +1,39 @@
|
||||
// Package v10 ...
|
||||
//
|
||||
// Description : v10 ...
|
||||
//
|
||||
// Author : go_developer@163.com<白茶清欢>
|
||||
//
|
||||
// Date : 2025-01-24 17:29
|
||||
package v10
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"git.zhangdeman.cn/gateway/validator/v10/define"
|
||||
"git.zhangdeman.cn/zhangdeman/consts"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestValidateDynamicStruct(t *testing.T) {
|
||||
err := ValidateDynamicStruct(map[string]any{
|
||||
"name": "zhang",
|
||||
"age": 15,
|
||||
}, map[string]define.FieldValidateGenerateConfig{
|
||||
"name": {
|
||||
Field: "name",
|
||||
RuleGroup: nil,
|
||||
RuleSimple: define.GenerateRuleExpressConfig{
|
||||
Rule: consts.ValidatorRuleCommonRequired,
|
||||
},
|
||||
},
|
||||
"age": {
|
||||
Field: "age",
|
||||
RuleGroup: nil,
|
||||
RuleSimple: define.GenerateRuleExpressConfig{
|
||||
Rule: consts.ValidatorRuleCommonMax,
|
||||
ParamList: []any{17},
|
||||
},
|
||||
},
|
||||
})
|
||||
fmt.Println(err)
|
||||
}
|
Reference in New Issue
Block a user