如何使用自定义验证器验证结构数据类型? [英] How can I validate a struct datatype with a custom validator?
问题描述
我正在使用 go-playground/validator/v10
来验证某些输入,并且在使用自定义验证标签和功能时遇到了一些麻烦.问题在于,当其中一个结构字段是不同的结构时,不会调用该函数.这是一个例子:
I am using go-playground/validator/v10
to validate some input and have some trouble with custom validation tags and functions. The problem is that the function is not called when one of the struct fields is a different struct. This is an example:
type ChildStruct struct {
Value int
}
type ParentStruct struct {
Child ChildStruct `validate:"myValidate"`
}
func myValidate(fl validator.FieldLevel) bool {
fmt.Println("INSIDE MY VALIDATOR") // <- This is never printed
return false
}
func main() {
validator := validator.New()
validator.RegisterValidation("myValidate", myValidate)
data := &ParentStruct{
Child: ChildStruct{
Value: 10,
},
}
validateErr := validator.Struct(data)
if validateErr != nil { // <- This is always nil since MyValidate is never called
fmt.Println("GOT ERROR")
fmt.Println(validateErr)
}
fmt.Println("DONE")
}
如果我将parentStruct更改为:
If I change the parentStruct to:
type ParentStruct struct {
Child int `validate:"myValidate"`
}
一切正常.如果我将 validate:"myValidate"
部分添加到ChildStruct,它也可以工作,但是,返回的错误是说ChildStruct.Value是错误的,它应该说ParentStruct.孩子是错的.
everything works.
If I add the validate:"myValidate"
part to the ChildStruct it is also working, however, then the error that is returned is saying that the ChildStruct.Value is wrong when it should say that the ParentStruct.Child is wrong.
有人知道我在做什么错吗?
Anyone know what I am doing wrong?
推荐答案
搜索了一段时间之后,我终于找到了一个名为 RegisterCustomTypeFunc
的函数,该函数注册了一个自定义类型,这将使go-playground/validator/v10
对其进行验证.因此,解决方案是将以下内容添加到问题的示例中:
After searching for a while I finally found a function called RegisterCustomTypeFunc
which registers a custom type which will make it possible for go-playground/validator/v10
to validate it. So the solution is to add the following to the example in the question:
func childStructCustomTypeFunc(field reflect.Value) interface{} {
if value, ok := field.Interface().(ChildStruct); ok {
return value.Value
}
return nil
}
与:
validator.RegisterCustomTypeFunc(childStructCustomTypeFunc, ChildStruct{})
现在,验证器将进入 myValidate
函数,并且返回消息将是 ParentStruct.Child
字段的错误
Now the validator will go into the myValidate
function and the return message will be an error for the ParentStruct.Child
field
这篇关于如何使用自定义验证器验证结构数据类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!