Skip to content

Commit

Permalink
fix(validator): get the specified error message of a nested field
Browse files Browse the repository at this point in the history
Change-Id: Ib99bf0c79015b30c8cb4467c775b43a5f81d416d
  • Loading branch information
andeya committed Feb 14, 2020
1 parent 2544665 commit 3a3a9ef
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 23 deletions.
21 changes: 4 additions & 17 deletions validator/validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,12 +61,6 @@ func (v *Validator) Validate(value interface{}, checkAll ...bool) error {
if len(checkAll) > 0 {
all = checkAll[0]
}
type ErrInfo struct {
selector string
path string
te *tagexpr.TagExpr
}
var errInfos = make([]*ErrInfo, 0, 8)
var errs = make([]error, 0, 8)
v.vm.RunAny(value, func(te *tagexpr.TagExpr, err error) error {
if err != nil {
Expand Down Expand Up @@ -97,11 +91,10 @@ func (v *Validator) Validate(value interface{}, checkAll ...bool) error {
}
}
}
errInfos = append(errInfos, &ErrInfo{
selector: eh.StringSelector(),
path: eh.Path(),
te: te,
})
errs = append(errs, v.errFactory(
eh.Path(),
eh.TagExpr().EvalString(eh.StringSelector()+tagexpr.ExprNameSeparator+ErrMsgExprName),
))
if all {
return nil
}
Expand All @@ -112,12 +105,6 @@ func (v *Validator) Validate(value interface{}, checkAll ...bool) error {
}
return nil
})
for _, info := range errInfos {
errs = append(errs, v.errFactory(
info.path,
info.te.EvalString(info.selector+tagexpr.ExprNameSeparator+ErrMsgExprName),
))
}
switch len(errs) {
case 0:
return nil
Expand Down
12 changes: 6 additions & 6 deletions validator/validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,7 +104,7 @@ func TestIssue3(t *testing.T) {

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

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

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

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

type B struct {
F1 *C `vd:"$!=nil"`
Expand Down

0 comments on commit 3a3a9ef

Please sign in to comment.