-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Feature] When customizing validation rules, is it possible to return the corresponding binding structure or map, or even their reflection objects? ? ? #2891
Comments
@shuqingzai 你检查一下这个输入参数是不是你想要的。另外, |
可以参考内置的规则实现。 |
You can refer to the built-in rule implementation. |
|
抱歉,我没能理解你的意思 @hailaz |
@shuqingzai 大概写了个示例,不算特别完善,也不代表最优解。只提供思路 // VailEnum 校验枚举值是否合法
type VailEnum interface {
IsVailEnum() bool
}
type IEnum int
const (
EnumUnknown IEnum = 0
EnumEmail IEnum = 1
EnumName IEnum = 2
)
func (e IEnum) IsVailEnum() bool {
fmt.Println("IsVailEnum")
return e == EnumEmail || e == EnumName
}
// TestMyEmnus description
//
// createTime: 2023-08-29 15:58:10
//
// author: hailaz
func TestMyEmnus(t *testing.T) {
rule := "in-enums"
gvalid.RegisterRule(
rule,
func(ctx context.Context, in gvalid.RuleFuncInput) error {
// typeName := reflect.TypeOf(in.Data.Val())
// fmt.Println("Type name:", typeName.Name(), in.Field)
// TODO:输入的可能不是结构体
// 获取输入的结构体的所有字段
fields, _ := gstructs.Fields(gstructs.FieldsInput{
Pointer: in.Data.Val(),
RecursiveOption: 0,
})
// 找到对应的字段进行判断
for _, v := range fields {
fmt.Println("Field name:", v.Field.Name)
if v.Field.Name == in.Field {
// 获取字段类型
t := v.Value.Type()
// 判断是否实现了接口
if t.Implements(reflect.TypeOf((*VailEnum)(nil)).Elem()) {
fmt.Println("实现了接口")
// 执行接口方法
res := v.Value.MethodByName("IsVailEnum").Call(nil)
if res[0].Bool() {
return nil
} else {
return errors.New(in.Message)
}
}
}
}
return nil
},
)
gtest.C(t, func(t *gtest.T) {
type Test struct {
UserType IEnum `v:"in-enums#值不正确"`
}
st := Test{
UserType: 0,
}
err := g.Validator().Data(st).Run(ctx)
t.AssertNil(err)
})
} |
@hailaz 谢谢你的回复,我觉得你的方法是可行,但是如果 #2890 (comment) 得到解决,我可以直接获取原始的数据结构与数据内容 使用 @gqcn 提供的方法
|
目前自定义规则中入参为:
gf/util/gvalid/gvalid_register.go
Line 23 in cf29927
Field
字段,在做通用性规则时,没法获取原来的struct
,受限性挺大的比如:我定义一个枚举类型,我只想传入的值在枚举值的一部分范围,而不是所有
需要实现的自定义大致规则如下:
允许用户可以操作绑定的结构体或 map (可能新增的字段
in.OrgType
),让Field
发挥他的价值,用户自定义规则更加自由1. What version of
Go
and system type/arch are you using?#-> % go version go version go1.21.0 darwin/amd64
2. What version of
GoFrame
are you using?3. Can this issue be re-produced with the latest release?
是的
4. What did you do?
5. What did you expect to see?
6. What did you see instead?
The text was updated successfully, but these errors were encountered: