From f2078f769615f1774abe2047eff6b770591e4275 Mon Sep 17 00:00:00 2001 From: Vijay Nallagatla Date: Sun, 19 Mar 2023 21:14:38 +0200 Subject: [PATCH] Fix unique validator for map with Pointer value (#1062) --- baked_in.go | 10 ++++++++-- validator_test.go | 6 ++++++ 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/baked_in.go b/baked_in.go index eda5814..ef9e055 100644 --- a/baked_in.go +++ b/baked_in.go @@ -315,11 +315,17 @@ func isUnique(fl FieldLevel) bool { } return field.Len() == m.Len() case reflect.Map: - m := reflect.MakeMap(reflect.MapOf(field.Type().Elem(), v.Type())) + var m reflect.Value + if field.Type().Elem().Kind() == reflect.Ptr { + m = reflect.MakeMap(reflect.MapOf(field.Type().Elem().Elem(), v.Type())) + } else { + m = reflect.MakeMap(reflect.MapOf(field.Type().Elem(), v.Type())) + } for _, k := range field.MapKeys() { - m.SetMapIndex(field.MapIndex(k), v) + m.SetMapIndex(reflect.Indirect(field.MapIndex(k)), v) } + return field.Len() == m.Len() default: panic(fmt.Sprintf("Bad field type %T", field.Interface())) diff --git a/validator_test.go b/validator_test.go index 0f43db8..e2a608f 100644 --- a/validator_test.go +++ b/validator_test.go @@ -9890,6 +9890,12 @@ func TestUniqueValidation(t *testing.T) { {map[string]string{"one": "a", "two": "a"}, false}, {map[string]interface{}{"one": "a", "two": "a"}, false}, {map[string]interface{}{"one": "a", "two": 1, "three": "b", "four": 1}, false}, + {map[string]*string{"one": stringPtr("a"), "two": stringPtr("a")}, false}, + {map[string]*string{"one": stringPtr("a"), "two": stringPtr("b")}, true}, + {map[string]*int{"one": intPtr(1), "two": intPtr(1)}, false}, + {map[string]*int{"one": intPtr(1), "two": intPtr(2)}, true}, + {map[string]*float64{"one": float64Ptr(1.1), "two": float64Ptr(1.1)}, false}, + {map[string]*float64{"one": float64Ptr(1.1), "two": float64Ptr(1.2)}, true}, } validate := New()