Skip to content

Commit d70803d

Browse files
authored
Fix nested structs field names (#101)
1 parent b37d688 commit d70803d

File tree

2 files changed

+34
-8
lines changed

2 files changed

+34
-8
lines changed

validator.go

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -304,21 +304,24 @@ func (mv *Validator) validateField(fieldDef reflect.StructField, fieldVal reflec
304304
}
305305

306306
// no-op if field is not a struct, interface, array, slice or map
307+
fn := mv.fieldName(fieldDef)
307308
mv.deepValidateCollection(fieldVal, m, func() string {
308-
return fieldDef.Name
309+
return fn
309310
})
310311

311312
if len(errs) > 0 {
312-
n := fieldDef.Name
313+
m[fn] = errs
314+
}
315+
return nil
316+
}
313317

314-
if mv.printJSON {
315-
if jn := parseName(fieldDef.Tag.Get("json")); jn != "" {
316-
n = jn
317-
}
318+
func (mv *Validator) fieldName(fieldDef reflect.StructField) string {
319+
if mv.printJSON {
320+
if jsonTagValue, ok := fieldDef.Tag.Lookup("json"); ok {
321+
return parseName(jsonTagValue)
318322
}
319-
m[n] = errs
320323
}
321-
return nil
324+
return fieldDef.Name
322325
}
323326

324327
func (mv *Validator) deepValidateCollection(f reflect.Value, m ErrorMap, fnameFn func() string) {

validator_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,10 @@ func (i Impl2) Foo() string {
5959
return i.F
6060
}
6161

62+
type NestedStruct struct {
63+
A string `validate:"nonzero" json:"a"`
64+
}
65+
6266
type TestStruct struct {
6367
A int `validate:"nonzero" json:"a"`
6468
B string `validate:"len=8,min=6,max=4"`
@@ -72,6 +76,12 @@ type TestStruct struct {
7276
E I `validate:nonzero`
7377
}
7478

79+
type TestCompositedStruct struct {
80+
NestedStruct `json:""`
81+
OtherNested NestedStruct `json:"otherNested"`
82+
Items []NestedStruct `json:"nestedItems"`
83+
}
84+
7585
func (ms *MySuite) TestValidate(c *C) {
7686
t := TestStruct{
7787
A: 0,
@@ -678,6 +688,19 @@ func (ms *MySuite) TestJSONPrint(c *C) {
678688
c.Assert(errs["a"], HasError, validator.ErrZeroValue)
679689
}
680690

691+
func (ms *MySuite) TestPrintNestedJson(c *C) {
692+
t := TestCompositedStruct{
693+
Items: []NestedStruct{{}},
694+
}
695+
err := validator.WithPrintJSON(true).Validate(t)
696+
c.Assert(err, NotNil)
697+
errs, ok := err.(validator.ErrorMap)
698+
c.Assert(ok, Equals, true)
699+
c.Assert(errs["a"], HasError, validator.ErrZeroValue)
700+
c.Assert(errs["otherNested.a"], HasError, validator.ErrZeroValue)
701+
c.Assert(errs["nestedItems[0].a"], HasError, validator.ErrZeroValue)
702+
}
703+
681704
func (ms *MySuite) TestJSONPrintOff(c *C) {
682705
t := TestStruct{
683706
A: 0,

0 commit comments

Comments
 (0)