Skip to content

Commit

Permalink
Merge pull request #164 from OscarVanL/master
Browse files Browse the repository at this point in the history
  • Loading branch information
inhere authored Aug 25, 2022
2 parents 2223675 + 59bcae3 commit 48e0d19
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 = []string{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 override with no specified field applies to all validation errors if SkipOnError=false is set in
// global options
Config(func(opt *GlobalOption) {
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.Contains(v.Errors.String(), "BirthDay")
is.Contains(v.Errors.String(), "max_len: 出生日期有误")
is.Contains(v.Errors.String(), "date: 出生日期有误")

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

// with field tag: json
Expand Down

0 comments on commit 48e0d19

Please sign in to comment.