英文:
golang gookit validate does not work with global custom validator
问题
我正在尝试使用Go语言的go-kit验证器并添加自定义验证器,但是该函数从未被调用。
package main
import (
"fmt"
"github.com/gookit/validate"
)
type Sample struct {
Name string `json:"name" validate:"required"`
Address string `json:"address" validate:"required"`
Payment string `json:"payment" validate:"payment_method"`
}
func main() {
validate.AddValidator("payment_method", func(val interface{}) bool {
value, ok := val.(string)
fmt.Println(value)
if !ok {
return false
}
if value != "hello" {
return false
}
return true
})
s := Sample{Name: "name", Address: "address", Payment: ""}
v := validate.Struct(&s)
res := v.Validate()
if !res {
fmt.Println(v.Errors.OneError())
} else {
fmt.Println("SUCCESS")
}
}
结果始终为成功,并且自定义验证器从未被调用。可以直接在Go Playground上运行代码。
英文:
I am trying to use golang gookit validator and adding custom validator, but the function never got fired.
package main
import (
"fmt"
"github.com/gookit/validate"
)
type Sample struct {
Name string `json:"name" validate:"required"`
Addres string `json:"address" validate:"required"`
Payment string `json:"payment" validate:"payment_method"`
}
func main() {
validate.AddValidator("payment_method", func(val interface{}) bool {
value, ok := val.(string)
fmt.Println(value)
if !ok {
return false
}
if value != "hello" {
return false
}
return true
})
s := Sample{Name: "name", Addres: "address", Payment: ""}
v := validate.Struct(&s)
res := v.Validate()
if !res {
fmt.Println(v.Errors.OneError())
} else {
fmt.Println("SUCCESS")
}
}
The result will be always success and the custom validator never get called. Directly on go playground
答案1
得分: 0
你需要在config中明确指出,不要跳过空值,像下面这样:
validate.Config(func(opt *validate.GlobalOption) {
opt.SkipOnEmpty = false
})
然后运行代码,它就会起作用。
英文:
You need to explicitly mention in the config,
> not to skip empty values
like below:
validate.Config(func(opt *validate.GlobalOption) {
opt.SkipOnEmpty = false
})
Then, run the code, it will work
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论