Skip to content

Commit

Permalink
🐛 fix: error when using custom filter with pointer to slice of string…
Browse files Browse the repository at this point in the history
…s. see #255
  • Loading branch information
inhere committed Jan 23, 2024
1 parent 46c37da commit 4491213
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 1 deletion.
2 changes: 1 addition & 1 deletion data_source.go
Original file line number Diff line number Diff line change
Expand Up @@ -666,7 +666,7 @@ func (d *StructData) Set(field string, val any) (newVal any, err error) {

// Notice: need convert value type
// - check whether you can direct convert type
rftVal := reflect.ValueOf(val)
rftVal := removeValuePtr(reflect.ValueOf(val))
if rftVal.Type().ConvertibleTo(fv.Type()) {
fv.Set(rftVal.Convert(fv.Type()))
return val, nil
Expand Down
47 changes: 47 additions & 0 deletions issues_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -1709,3 +1709,50 @@ func TestIssues_252(t *testing.T) {
ok := v.Validate()
assert.True(t, ok)
}

// https://github.com/gookit/validate/issues/255
// Error when using custom filter with pointer to slice of strings #255
func TestIssues_255(t *testing.T) {
type Request struct {
PtrStringSlice *[]string `json:"string_slice" filter:"ptrTrimStrings" validate:"strings"`
}

t.Run("return pointer", func(t *testing.T) {
ss1 := []string{" foobar "}
req := &Request{PtrStringSlice: &ss1}
v := validate.New(req)

v.AddFilters(validate.M{
"ptrTrimStrings": func(val *[]string) *[]string {
trimmedSlice := make([]string, len(*val))
for i, str := range *val {
trimmedSlice[i] = strings.TrimSpace(str)
}
return &trimmedSlice
},
})

assert.True(t, v.Validate())
assert.Equal(t, []string{"foobar"}, *req.PtrStringSlice)
})

t.Run("return value", func(t *testing.T) {
ss1 := []string{" foobar "}
req := &Request{PtrStringSlice: &ss1}
v := validate.New(req)

// return value []string
v.AddFilters(validate.M{
"ptrTrimStrings": func(val *[]string) []string {
trimmedSlice := make([]string, len(*val))
for i, str := range *val {
trimmedSlice[i] = strings.TrimSpace(str)
}
return trimmedSlice
},
})

assert.True(t, v.Validate())
assert.Equal(t, []string{"foobar"}, *req.PtrStringSlice)
})
}

0 comments on commit 4491213

Please sign in to comment.