Skip to content

Commit

Permalink
Fix unique validator for map with Pointer value (#1062)
Browse files Browse the repository at this point in the history
  • Loading branch information
vijaynallagatla committed Mar 19, 2023
1 parent ef342b6 commit f2078f7
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
10 changes: 8 additions & 2 deletions baked_in.go
Expand Up @@ -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()))
Expand Down
6 changes: 6 additions & 0 deletions validator_test.go
Expand Up @@ -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()
Expand Down

0 comments on commit f2078f7

Please sign in to comment.