From 06e9f9497026730c8bfb6ac7ae6337a250024f12 Mon Sep 17 00:00:00 2001 From: Jimmy Pettersson Date: Fri, 22 Aug 2014 15:32:41 +0200 Subject: [PATCH 1/2] Added nil check for embedded structs --- binding/binding.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/binding/binding.go b/binding/binding.go index bb6cbde2..92ede2b8 100644 --- a/binding/binding.go +++ b/binding/binding.go @@ -176,6 +176,10 @@ func Validate(obj interface{}) error { if strings.Index(field.Tag.Get("binding"), "required") > -1 { fieldType := field.Type.Kind() if fieldType == reflect.Struct { + if reflect.DeepEqual(zero, fieldValue) { + return errors.New("Required " + field.Name) + } + err := Validate(fieldValue) if err != nil { return err From d7f4db4ad34c2d4abf93fd0fce461f56cea4291d Mon Sep 17 00:00:00 2001 From: Jimmy Pettersson Date: Fri, 22 Aug 2014 15:54:26 +0200 Subject: [PATCH 2/2] Added reference to parent structs --- binding/binding.go | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/binding/binding.go b/binding/binding.go index 92ede2b8..3670fd97 100644 --- a/binding/binding.go +++ b/binding/binding.go @@ -151,7 +151,7 @@ func ensureNotPointer(obj interface{}) { } } -func Validate(obj interface{}) error { +func Validate(obj interface{}, parents ...string) error { typ := reflect.TypeOf(obj) val := reflect.ValueOf(obj) @@ -179,13 +179,16 @@ func Validate(obj interface{}) error { if reflect.DeepEqual(zero, fieldValue) { return errors.New("Required " + field.Name) } - - err := Validate(fieldValue) + err := Validate(fieldValue, field.Name) if err != nil { return err } } else if reflect.DeepEqual(zero, fieldValue) { - return errors.New("Required " + field.Name) + if len(parents) > 0 { + return errors.New("Required " + field.Name + " on " + parents[0]) + } else { + return errors.New("Required " + field.Name) + } } else if fieldType == reflect.Slice && field.Type.Elem().Kind() == reflect.Struct { err := Validate(fieldValue) if err != nil {