Skip to content

Commit

Permalink
Fix nested structs field names (#101)
Browse files Browse the repository at this point in the history
  • Loading branch information
kirr committed Apr 5, 2022
1 parent b37d688 commit d70803d
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 8 deletions.
19 changes: 11 additions & 8 deletions validator.go
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
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

0 comments on commit d70803d

Please sign in to comment.