字符串验证 : 支持配置参数传了的场景下,不允许为空验证

This commit is contained in:
白茶清欢 2024-11-01 17:22:41 +08:00
parent e5b2e1a377
commit c35d379a26
2 changed files with 69 additions and 1 deletions

View File

@ -116,6 +116,11 @@ func handleString(inputVal any, rule *define.FieldRule) (string, error) {
if err = util.ConvertAssign(&formatData, inputVal); nil != err { if err = util.ConvertAssign(&formatData, inputVal); nil != err {
return "", err return "", err
} }
// 判断空字符串
if !rule.AllowEmpty && formatData == "" && rule.IsRequired {
// 必传且不允许空字符串
return "", fmt.Errorf("%v : data type is string empty, field is required and empty value is not allowed", rule.Path)
}
if nil == rule.ValueLimit { if nil == rule.ValueLimit {
return formatData, nil return formatData, nil
} }

View File

@ -10,6 +10,7 @@ package validator
import ( import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"git.zhangdeman.cn/gateway/validator/define"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/tidwall/gjson" "github.com/tidwall/gjson"
"testing" "testing"
@ -19,7 +20,7 @@ func TestRun(t *testing.T) {
sourceData := map[string]interface{}{ sourceData := map[string]interface{}{
"name": "白茶清欢", "name": "白茶清欢",
} }
_ = Run(sourceData, nil) _ = Run(sourceData, nil, nil)
byteData, _ := json.Marshal(sourceData) byteData, _ := json.Marshal(sourceData)
fmt.Println(string(byteData)) fmt.Println(string(byteData))
} }
@ -42,3 +43,65 @@ func Test_getDataStatus(t *testing.T) {
}) })
} }
} }
// TestRunRequired 测试字段必传
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 16:48 2024/11/1
func TestRunRequired(t *testing.T) {
sourceData := map[string]interface{}{
"name": "白茶清欢",
}
ruleListForNotFound := []*define.FieldRule{
&define.FieldRule{
Path: "name1",
Type: "string",
DisableRewrite: false,
DefaultValue: nil,
IsRequired: true,
AllowEmpty: false,
AllowZero: false,
AllowNil: false,
DisableAutoTrimSpace: false,
DisableAutoConvert: false,
RequiredConditionGroup: nil,
ValueLimit: nil,
SliceConfig: nil,
MapConfig: nil,
},
}
err := Run(sourceData, ruleListForNotFound, nil)
if nil != err {
fmt.Println(err.Error())
}
assert.Error(t, err)
sourceData = map[string]interface{}{
"name": "",
}
ruleListForEmpty := []*define.FieldRule{
&define.FieldRule{
Path: "name",
Type: "string",
DisableRewrite: false,
DefaultValue: nil,
IsRequired: true,
AllowEmpty: false,
AllowZero: false,
AllowNil: false,
DisableAutoTrimSpace: false,
DisableAutoConvert: false,
RequiredConditionGroup: nil,
ValueLimit: nil,
SliceConfig: nil,
MapConfig: nil,
},
}
err = Run(sourceData, ruleListForEmpty, nil)
if nil != err {
fmt.Println(err.Error())
}
assert.Error(t, err)
}