From 94c718582636e8ec7d9ec3d51338e582231ad6a0 Mon Sep 17 00:00:00 2001 From: xyqweb <12839346+xyqweb@users.noreply.github.com> Date: Tue, 7 May 2024 20:36:55 +0800 Subject: [PATCH] util/gvalid: fix slice enums verification failed (#3566) --- util/gvalid/gvalid_z_unit_feature_rule_test.go | 10 ++++++++++ util/gvalid/internal/builtin/builtin_enums.go | 5 +++++ 2 files changed, 15 insertions(+) diff --git a/util/gvalid/gvalid_z_unit_feature_rule_test.go b/util/gvalid/gvalid_z_unit_feature_rule_test.go index 853badcf582..c4c10d615a5 100755 --- a/util/gvalid/gvalid_z_unit_feature_rule_test.go +++ b/util/gvalid/gvalid_z_unit_feature_rule_test.go @@ -1577,6 +1577,10 @@ func Test_Enums(t *testing.T) { Id int Enums EnumsTest `v:"enums"` } + type SliceParams struct { + Id int + Enums []EnumsTest `v:"foreach|enums"` + } oldEnumsJson, err := gtag.GetGlobalEnums() t.AssertNil(err) @@ -1596,5 +1600,11 @@ func Test_Enums(t *testing.T) { Enums: "c", }).Run(ctx) t.Assert(err, "The Enums value `c` should be in enums of: [\"a\",\"b\"]") + + err = g.Validator().Data(&SliceParams{ + Id: 1, + Enums: []EnumsTest{EnumsTestA, EnumsTestB}, + }).Run(ctx) + t.AssertNil(err) }) } diff --git a/util/gvalid/internal/builtin/builtin_enums.go b/util/gvalid/internal/builtin/builtin_enums.go index b2f12faf477..071ec4d11fd 100644 --- a/util/gvalid/internal/builtin/builtin_enums.go +++ b/util/gvalid/internal/builtin/builtin_enums.go @@ -9,6 +9,7 @@ package builtin import ( "errors" "fmt" + "reflect" "github.com/gogf/gf/v2/errors/gcode" "github.com/gogf/gf/v2/errors/gerror" @@ -47,6 +48,10 @@ func (r RuleEnums) Run(in RunInput) error { pkgPath = in.ValueType.PkgPath() typeName = in.ValueType.Name() ) + if in.ValueType.Kind() == reflect.Slice { + pkgPath = in.ValueType.Elem().PkgPath() + typeName = in.ValueType.Elem().Name() + } if pkgPath == "" { return gerror.NewCodef( gcode.CodeInvalidOperation,