Skip to content

Commit

Permalink
Merge pull request #134 from asdine/fix/errorsByField
Browse files Browse the repository at this point in the history
Fix ErrorsByField when using custom validators
  • Loading branch information
asaskevich committed Jul 15, 2016
2 parents 136d678 + 186f6a1 commit 593d645
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 1 deletion.
5 changes: 4 additions & 1 deletion validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -903,7 +903,10 @@ func ErrorsByField(e error) map[string]string {
m[e.(Error).Name] = e.(Error).Err.Error()
case Errors:
for _, item := range e.(Errors).Errors() {
m[item.(Error).Name] = item.(Error).Err.Error()
n := ErrorsByField(item)
for k, v := range n {
m[k] = v
}
}
}

Expand Down
29 changes: 29 additions & 0 deletions validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2303,6 +2303,35 @@ func TestErrorsByField(t *testing.T) {
t.Errorf("Expected ErrorsByField(%q) to be %v, got %v", test.param, test.expected, actual)
}
}

type StructWithCustomValidation struct {
Email string `valid:"email"`
ID string `valid:"falseValidation"`
}

CustomTypeTagMap.Set("falseValidation", CustomTypeValidator(func(i interface{}, o interface{}) bool {
return false
}))

tests = []struct {
param string
expected string
}{
{"Email", "My123 does not validate as email"},
{"ID", "duck13126 does not validate as falseValidation"},
}
s := &StructWithCustomValidation{Email: "My123", ID: "duck13126"}
_, err = ValidateStruct(s)
errs = ErrorsByField(err)
if len(errs) != 2 {
t.Errorf("There should only be 2 errors but got %v", len(errs))
}

for _, test := range tests {
if actual, ok := errs[test.param]; !ok || actual != test.expected {
t.Errorf("Expected ErrorsByField(%q) to be %v, got %v", test.param, test.expected, actual)
}
}
}

func TestValidateStructPointers(t *testing.T) {
Expand Down

0 comments on commit 593d645

Please sign in to comment.