Skip to content

Commit 3a3a9ef

Browse files
committed
fix(validator): get the specified error message of a nested field
Change-Id: Ib99bf0c79015b30c8cb4467c775b43a5f81d416d
1 parent 2544665 commit 3a3a9ef

File tree

2 files changed

+10
-23
lines changed

2 files changed

+10
-23
lines changed

validator/validator.go

Lines changed: 4 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -61,12 +61,6 @@ func (v *Validator) Validate(value interface{}, checkAll ...bool) error {
6161
if len(checkAll) > 0 {
6262
all = checkAll[0]
6363
}
64-
type ErrInfo struct {
65-
selector string
66-
path string
67-
te *tagexpr.TagExpr
68-
}
69-
var errInfos = make([]*ErrInfo, 0, 8)
7064
var errs = make([]error, 0, 8)
7165
v.vm.RunAny(value, func(te *tagexpr.TagExpr, err error) error {
7266
if err != nil {
@@ -97,11 +91,10 @@ func (v *Validator) Validate(value interface{}, checkAll ...bool) error {
9791
}
9892
}
9993
}
100-
errInfos = append(errInfos, &ErrInfo{
101-
selector: eh.StringSelector(),
102-
path: eh.Path(),
103-
te: te,
104-
})
94+
errs = append(errs, v.errFactory(
95+
eh.Path(),
96+
eh.TagExpr().EvalString(eh.StringSelector()+tagexpr.ExprNameSeparator+ErrMsgExprName),
97+
))
10598
if all {
10699
return nil
107100
}
@@ -112,12 +105,6 @@ func (v *Validator) Validate(value interface{}, checkAll ...bool) error {
112105
}
113106
return nil
114107
})
115-
for _, info := range errInfos {
116-
errs = append(errs, v.errFactory(
117-
info.path,
118-
info.te.EvalString(info.selector+tagexpr.ExprNameSeparator+ErrMsgExprName),
119-
))
120-
}
121108
switch len(errs) {
122109
case 0:
123110
return nil

validator/validator_test.go

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -104,7 +104,7 @@ func TestIssue3(t *testing.T) {
104104

105105
func TestIssue4(t *testing.T) {
106106
type C struct {
107-
Index *int32 `vd:"$!=nil"`
107+
Index *int32 `vd:"@:$!=nil;msg:'index is nil'"`
108108
Index2 *int32 `vd:"$!=nil"`
109109
Index3 *int32 `vd:"$!=nil"`
110110
}
@@ -119,13 +119,13 @@ func TestIssue4(t *testing.T) {
119119
assert.NoError(t, v.Validate(a))
120120

121121
a = &A{F1: new(C)}
122-
assert.EqualError(t, v.Validate(a), "invalid parameter: F1.Index")
122+
assert.EqualError(t, v.Validate(a), "index is nil")
123123

124-
a = &A{F2: map[string]*C{"": nil}}
125-
assert.EqualError(t, v.Validate(a), "invalid parameter: F2{}.Index")
124+
a = &A{F2: map[string]*C{"": &C{Index: new(int32)}}}
125+
assert.EqualError(t, v.Validate(a), "invalid parameter: F2{}.Index2")
126126

127-
a = &A{F3: []*C{new(C)}}
128-
assert.EqualError(t, v.Validate(a), "invalid parameter: F3[0].Index")
127+
a = &A{F3: []*C{{Index: new(int32)}}}
128+
assert.EqualError(t, v.Validate(a), "invalid parameter: F3[0].Index2")
129129

130130
type B struct {
131131
F1 *C `vd:"$!=nil"`

0 commit comments

Comments
 (0)