From 90f28e0db01787be69a61ebb1db69de1d0671710 Mon Sep 17 00:00:00 2001 From: Dex Chen Date: Wed, 13 Oct 2021 12:24:41 -0600 Subject: [PATCH 1/2] Fix issue 454 validation of map (json) struct --- validator.go | 7 ++++++- validator_test.go | 29 +++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/validator.go b/validator.go index 46ecfc8..e79c42e 100644 --- a/validator.go +++ b/validator.go @@ -1131,7 +1131,7 @@ func ValidateStruct(s interface{}) (bool, error) { } if (valueField.Kind() == reflect.Struct || (valueField.Kind() == reflect.Ptr && valueField.Elem().Kind() == reflect.Struct)) && - typeField.Tag.Get(tagName) != "-" { + typeField.Tag.Get(tagName) != "-" { var err error structResult, err = ValidateStruct(valueField.Interface()) if err != nil { @@ -1680,6 +1680,11 @@ func typeCheck(v reflect.Value, t reflect.StructField, o reflect.Value, options if v.IsNil() { return true, nil } + // Fix https://github.com/asaskevich/govalidator/issues/454 -- check if the value/interface is not struct, like string + val := reflect.ValueOf(v.Interface()) + if val.Kind() != reflect.Struct { + return typeCheck(val, t, o, options) + } return ValidateStruct(v.Interface()) case reflect.Ptr: // If the value is a pointer then checks its element diff --git a/validator_test.go b/validator_test.go index bff8613..fa9791f 100644 --- a/validator_test.go +++ b/validator_test.go @@ -3865,3 +3865,32 @@ func TestIsE164(t *testing.T) { } } } + +func TestMapInterfaceFieldValidation(t *testing.T) { + type address struct { + Properties map[string]interface{} `valid:"required"` + } + + var tests = []struct { + args address + expected bool + }{ + { + args: address{ + Properties: map[string]interface{}{"filter": "v1"}}, + expected: true, + }, + { + args: address{ + Properties: nil}, + expected: false, + }, + } + for _, test := range tests { + ok, err := ValidateStruct(test.args) + + if ok != test.expected { + t.Errorf("expected validation: %v and got: %v, error: %s", test.expected, ok, err) + } + } +} From 07e613a7addeb3da2396879066e0806b53e63c4b Mon Sep 17 00:00:00 2001 From: Dex Chen Date: Wed, 13 Oct 2021 13:20:41 -0600 Subject: [PATCH 2/2] Remove extra space --- validator.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/validator.go b/validator.go index e79c42e..85f82e4 100644 --- a/validator.go +++ b/validator.go @@ -1131,7 +1131,7 @@ func ValidateStruct(s interface{}) (bool, error) { } if (valueField.Kind() == reflect.Struct || (valueField.Kind() == reflect.Ptr && valueField.Elem().Kind() == reflect.Struct)) && - typeField.Tag.Get(tagName) != "-" { + typeField.Tag.Get(tagName) != "-" { var err error structResult, err = ValidateStruct(valueField.Interface()) if err != nil {