Fix unique validator for map with Pointer value (#1062)

pull/1081/head
Vijay Nallagatla 2 years ago committed by GitHub
parent ef342b6f7c
commit f2078f7696
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 10
      baked_in.go
  2. 6
      validator_test.go

@ -315,11 +315,17 @@ func isUnique(fl FieldLevel) bool {
} }
return field.Len() == m.Len() return field.Len() == m.Len()
case reflect.Map: 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() { for _, k := range field.MapKeys() {
m.SetMapIndex(field.MapIndex(k), v) m.SetMapIndex(reflect.Indirect(field.MapIndex(k)), v)
} }
return field.Len() == m.Len() return field.Len() == m.Len()
default: default:
panic(fmt.Sprintf("Bad field type %T", field.Interface())) panic(fmt.Sprintf("Bad field type %T", field.Interface()))

@ -9890,6 +9890,12 @@ func TestUniqueValidation(t *testing.T) {
{map[string]string{"one": "a", "two": "a"}, false}, {map[string]string{"one": "a", "two": "a"}, false},
{map[string]interface{}{"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]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() validate := New()

Loading…
Cancel
Save