gookit / validate

⚔ Go package for data validation and filtering. support Map, Struct, Form data. Go通用的数据验证与过滤库,使用简单,内置大部分常用验证、过滤器,支持自定义验证器、自定义消息、字段翻译。

Home Page:https://gookit.github.io/validate/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Error when using custom filter with pointer to slice of strings

kaptinlin opened this issue · comments

System (please complete the following information):

  • OS: linux
  • GO Version: 1.21.0
  • Pkg Version: the master latest

Describe the bug

When using a custom filter ptrTrimStrings to trim whitespace from each string in a pointer to a slice of strings, the validation fails with a type conversion error.

To Reproduce

package main

import (
	"strings"
	"github.com/gookit/validate"
)

func main() {
	validate.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
		},
	})

	type Request struct {
		PtrStringSlice *[]string `json:"string_slice" filter:"ptrTrimStrings" validate:"strings"`
	}
	stringSlice := []string{" foobar "}
	v := validate.New(&Request{
		PtrStringSlice: &stringSlice,
	})

	if err := v.Validate(); err != nil {
		panic(err)
	}
}

Expected behavior

The custom filter ptrTrimStrings should trim the whitespace from each string in the slice without any errors, and the validation should pass successfully.

Screenshots

N/A

Additional context

The error message received is:

"_filter": {
    "_filter": "PtrStringSlice: convert value type error"
}

This suggests that there might be an issue with the filter function's return type or the way the library handles the conversion of filtered values for pointer to slice fields.

hi @kaptinlin fixed in the latest codes.