From a7d4df6e6e8161c049fb9d55e3f3bb4fd5abd2f2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Fri, 21 Mar 2025 23:42:35 +0800 Subject: [PATCH] =?UTF-8?q?=E5=B5=8C=E5=A5=97=E7=BB=93=E6=9E=84=E4=B8=AD?= =?UTF-8?q?=E9=97=B4=E5=B1=82=E7=BA=A7=E6=94=AF=E6=8C=81=E9=AA=8C=E8=AF=81?= =?UTF-8?q?=E5=BF=85=E4=BC=A0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- validate.go | 13 ++++++++----- validate_test.go | 28 ++++++++++++++-------------- 2 files changed, 22 insertions(+), 19 deletions(-) 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))