Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 11 additions & 8 deletions validator.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
23 changes: 23 additions & 0 deletions validator_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"`
Expand All @@ -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,
Expand Down Expand Up @@ -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,
Expand Down