Skip to content

Commit

Permalink
make attempt to fix issue
Browse files Browse the repository at this point in the history
  • Loading branch information
OscarVanL committed Aug 25, 2022
1 parent 2223675 commit b65b3a4
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 10 deletions.
26 changes: 16 additions & 10 deletions data_source.go
Original file line number Diff line number Diff line change
Expand Up @@ -431,6 +431,7 @@ func (d *StructData) parseRulesFromTag(v *Validation) {
// eg: `message:"required:name is required|minLen:name min len is %d"`
func (d *StructData) loadMessagesFromTag(trans *Translator, field, vRule, vMsg string) {
var msgKey, vName string
var vNames []string

// only one message, use for first validator.
// eg: `message:"name is required"`
Expand All @@ -439,32 +440,37 @@ func (d *StructData) loadMessagesFromTag(trans *Translator, field, vRule, vMsg s
if strings.ContainsRune(vMsg, ':') {
nodes := strings.SplitN(vMsg, ":", 2)
vName = strings.TrimSpace(nodes[0])
vNames = []string{vName}
// first is validator name
vMsg = strings.TrimSpace(nodes[1])
}

if vName == "" {
// eg `validate:"required|date"`
vName = vRule
vNames = append(vNames, vRule)

if strings.ContainsRune(vRule, '|') {
nodes := strings.SplitN(vRule, "|", 2)
vName = nodes[0]
vNames = strings.Split(vRule, "|")
}

// has params for validator: "minLen:5"
if strings.ContainsRune(vName, ':') {
nodes := strings.SplitN(vRule, ":", 2)
vName = nodes[0]
for i, node := range vNames {
// has params for validator: "minLen:5"
if strings.ContainsRune(node, ':') {
tmp := strings.SplitN(node, ":", 2)
vNames[i] = tmp[0]
}
}
}

// if rName, has := validatorAliases[validator]; has {
// msgKey = field + "." + rName
// } else {
msgKey = field + "." + vName
// }

trans.AddMessage(msgKey, vMsg)
for _, name := range vNames {
msgKey = field + "." + name
trans.AddMessage(msgKey, vMsg)
}

return
}

Expand Down
26 changes: 26 additions & 0 deletions messages_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,32 @@ func TestMessageOnStruct(t *testing.T) {
v = Struct(s4)
is.False(v.Validate())
is.Equal("出生日期有误", v.Errors.One())

// Ensure message with no specified field applies to all validation errors on a single field if SkipOnError=false
// Set custom global options
Config(func(opt *GlobalOption) {
opt.SkipOnEmpty = false
opt.StopOnError = false
})

s5 := &struct {
Name string `validate:"string"`
BirthDay string `validate:"max_len:1|date" message:"出生日期有误"`
}{
"tom",
"ff",
}

v = Struct(s5)

is.False(v.Validate())
is.Equal("BirthDay:\n max_len: 出生日期有误\n date: 出生日期有误", v.Errors.String())

// Restore original global options
Config(func(opt *GlobalOption) {
opt.SkipOnEmpty = true
opt.StopOnError = true
})
}

// with field tag: json
Expand Down

0 comments on commit b65b3a4

Please sign in to comment.