From cc768b176db37d4bd0efee2572a0402ec5b8da6d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Yann=20Sala=C3=BCn?= <1910607+yansal@users.noreply.github.com> Date: Sun, 19 Mar 2023 20:22:03 +0100 Subject: [PATCH] fix unique= when struct field is a nil pointer (#1041) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fix https://github.com/go-playground/validator/issues/749 Co-authored-by: Yann Salaün --- baked_in.go | 9 +++++++-- validator_test.go | 1 + 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/baked_in.go b/baked_in.go index e8d17a7..dd4b331 100644 --- a/baked_in.go +++ b/baked_in.go @@ -312,10 +312,15 @@ func isUnique(fl FieldLevel) bool { } m := reflect.MakeMap(reflect.MapOf(sfTyp, v.Type())) + var fieldlen int for i := 0; i < field.Len(); i++ { - m.SetMapIndex(reflect.Indirect(reflect.Indirect(field.Index(i)).FieldByName(param)), v) + key := reflect.Indirect(reflect.Indirect(field.Index(i)).FieldByName(param)) + if key.IsValid() { + fieldlen++ + m.SetMapIndex(key, v) + } } - return field.Len() == m.Len() + return fieldlen == m.Len() case reflect.Map: var m reflect.Value if field.Type().Elem().Kind() == reflect.Ptr { diff --git a/validator_test.go b/validator_test.go index b8ebe64..07bc889 100644 --- a/validator_test.go +++ b/validator_test.go @@ -10043,6 +10043,7 @@ func TestUniqueValidationStructPtrSlice(t *testing.T) { }{ {A: stringPtr("one"), B: stringPtr("two")}, {A: stringPtr("one"), B: stringPtr("three")}, + {}, } tests := []struct {