diff --git a/validate.go b/validate.go index 55ba407..ceedbe6 100644 --- a/validate.go +++ b/validate.go @@ -71,15 +71,18 @@ type handle struct { // Run 执行验证 func (h *handle) Run() ([]byte, error) { for _, field := range h.fieldList { - if h.parentFieldTable[field.TargetPath] { - // 中间层级字段, 无需额外处理 - continue - } if len(field.Errmsg) == 0 { field.Errmsg = field.JsonTag + " : 参数校验不通过" } required, hasRequired := h.checkRequired(field) field.Required = required + if h.parentFieldTable[field.TargetPath] { + // 中间层级字段, 无需额外处理, 验一下必传就行 + if !gjson.GetBytes(h.sourceData, field.SourcePath).Exists() && field.Required { + return nil, errors.New(field.TargetPath + " : 数据源路径数据不存在 => " + field.SourcePath) + } + continue + } if field.Required && !hasRequired { if nil == field.RuleList { field.RuleList = make([]Rule, 0) @@ -102,7 +105,7 @@ func (h *handle) Run() ([]byte, error) { if err := serialize.JSON.UnmarshalWithNumber([]byte(h.formatVal), &val); nil != err { return nil, err } - if err := defaults.Set(&val); nil != err { + if err := defaults.Set(val); nil != err { // 默认值设置失败 return nil, err } diff --git a/validate_test.go b/validate_test.go index c21720c..705f302 100644 --- a/validate_test.go +++ b/validate_test.go @@ -51,20 +51,6 @@ func TestRun_Simple_Data(t *testing.T) { TargetPath: "user_age", Errmsg: "年龄必须在[1,2000]之间", }, - { - JsonTag: "company_name", - Type: consts.DataTypeString, - Required: false, - RuleList: []Rule{ - { - Tag: "required", - }, - }, - DefaultValue: "", - SourcePath: "company.name", - TargetPath: "company.company_name", - Errmsg: "公司名称必须在[1,20]之间", - }, { JsonTag: "company", Type: consts.DataTypeString, @@ -79,6 +65,20 @@ func TestRun_Simple_Data(t *testing.T) { TargetPath: "company", Errmsg: "公司信息必传", }, + { + JsonTag: "company_name", + Type: consts.DataTypeString, + Required: false, + RuleList: []Rule{ + { + Tag: "required", + }, + }, + DefaultValue: "", + SourcePath: "company.name", + TargetPath: "company.company_name", + Errmsg: "公司名称必须在[1,20]之间", + }, } res, err := Run(sourceByteData, fieldList) fmt.Println(err, string(res))