diff --git a/validator.go b/validator.go index 4d610be..b285876 100644 --- a/validator.go +++ b/validator.go @@ -304,21 +304,24 @@ func (mv *Validator) validateField(fieldDef reflect.StructField, fieldVal reflec } // no-op if field is not a struct, interface, array, slice or map + fn := mv.fieldName(fieldDef) mv.deepValidateCollection(fieldVal, m, func() string { - return fieldDef.Name + return fn }) if len(errs) > 0 { - n := fieldDef.Name + m[fn] = errs + } + return nil +} - if mv.printJSON { - if jn := parseName(fieldDef.Tag.Get("json")); jn != "" { - n = jn - } +func (mv *Validator) fieldName(fieldDef reflect.StructField) string { + if mv.printJSON { + if jsonTagValue, ok := fieldDef.Tag.Lookup("json"); ok { + return parseName(jsonTagValue) } - m[n] = errs } - return nil + return fieldDef.Name } func (mv *Validator) deepValidateCollection(f reflect.Value, m ErrorMap, fnameFn func() string) { diff --git a/validator_test.go b/validator_test.go index 0f4a8cf..1154357 100644 --- a/validator_test.go +++ b/validator_test.go @@ -59,6 +59,10 @@ func (i Impl2) Foo() string { return i.F } +type NestedStruct struct { + A string `validate:"nonzero" json:"a"` +} + type TestStruct struct { A int `validate:"nonzero" json:"a"` B string `validate:"len=8,min=6,max=4"` @@ -72,6 +76,12 @@ type TestStruct struct { E I `validate:nonzero` } +type TestCompositedStruct struct { + NestedStruct `json:""` + OtherNested NestedStruct `json:"otherNested"` + Items []NestedStruct `json:"nestedItems"` +} + func (ms *MySuite) TestValidate(c *C) { t := TestStruct{ A: 0, @@ -678,6 +688,19 @@ func (ms *MySuite) TestJSONPrint(c *C) { c.Assert(errs["a"], HasError, validator.ErrZeroValue) } +func (ms *MySuite) TestPrintNestedJson(c *C) { + t := TestCompositedStruct{ + Items: []NestedStruct{{}}, + } + err := validator.WithPrintJSON(true).Validate(t) + c.Assert(err, NotNil) + errs, ok := err.(validator.ErrorMap) + c.Assert(ok, Equals, true) + c.Assert(errs["a"], HasError, validator.ErrZeroValue) + c.Assert(errs["otherNested.a"], HasError, validator.ErrZeroValue) + c.Assert(errs["nestedItems[0].a"], HasError, validator.ErrZeroValue) +} + func (ms *MySuite) TestJSONPrintOff(c *C) { t := TestStruct{ A: 0,