Skip to content

Commit

Permalink
Fix accessing fields in composed structs (#733)
Browse files Browse the repository at this point in the history
  • Loading branch information
Michał Treter committed Apr 6, 2021
1 parent 514c9db commit ec1baac
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
5 changes: 4 additions & 1 deletion validator_instance.go
Expand Up @@ -414,7 +414,10 @@ func (v *Validate) StructPartialCtx(ctx context.Context, s interface{}, fields .
if len(flds) > 0 {

vd.misc = append(vd.misc[0:0], name...)
vd.misc = append(vd.misc, '.')
// Don't append empty name for unnamed structs
if len(vd.misc) != 0 {
vd.misc = append(vd.misc, '.')
}

for _, s := range flds {

Expand Down
32 changes: 32 additions & 0 deletions validator_test.go
Expand Up @@ -949,6 +949,38 @@ func TestStructPartial(t *testing.T) {
NotEqual(t, errs, nil)
AssertError(t, errs, "TestPartial.Anonymous.SubAnonStruct[0].Test", "TestPartial.Anonymous.SubAnonStruct[0].Test", "Test", "Test", "required")

// Test for unnamed struct
testStruct := &TestStruct{
String: "test",
}
unnamedStruct := struct {
String string `validate:"required" json:"StringVal"`
}{String: "test"}
composedUnnamedStruct := struct{ *TestStruct }{&TestStruct{String: "test"}}

errs = validate.StructPartial(testStruct, "String")
Equal(t, errs, nil)

errs = validate.StructPartial(unnamedStruct, "String")
Equal(t, errs, nil)

errs = validate.StructPartial(composedUnnamedStruct, "TestStruct.String")
Equal(t, errs, nil)

testStruct.String = ""
errs = validate.StructPartial(testStruct, "String")
NotEqual(t, errs, nil)
AssertError(t, errs, "TestStruct.String", "TestStruct.String", "String", "String", "required")

unnamedStruct.String = ""
errs = validate.StructPartial(unnamedStruct, "String")
NotEqual(t, errs, nil)
AssertError(t, errs, "String", "String", "String", "String", "required")

composedUnnamedStruct.String = ""
errs = validate.StructPartial(composedUnnamedStruct, "TestStruct.String")
NotEqual(t, errs, nil)
AssertError(t, errs, "TestStruct.String", "TestStruct.String", "String", "String", "required")
}

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

0 comments on commit ec1baac

Please sign in to comment.