嵌套结构中间层级支持验证必传
This commit is contained in:
parent
d973b5c5fc
commit
a7d4df6e6e
13
validate.go
13
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
|
||||
}
|
||||
|
@ -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))
|
||||
|
Loading…
x
Reference in New Issue
Block a user