如何解决如何使用验证程序v10验证null.v4包类型的结构字段?
我有一个结构,我正在尝试使用验证程序v10验证结构,该字段的字段可以是null.v4包中的null.XX类型。
type FooStruct struct {
Foo null.Int `json:"foo" binding:"nullIntMin=1"`
}
(显然)开箱即用,所以我想做一个自定义验证器。
var validateNullIntMin validator.Func = func(fl validator.FieldLevel) bool {
number,ok := fl.Field().Interface().(null.Int)
min := cToInt(fl.Param())
if ok {
if number.Value > min && number.Valid {
return false
}
}
return true
}
func cToInt(param string) int64 {
i,err := strconv.ParseInt(param,64)
panic(err)
return i
}
问题在于数据从未得到验证。甚至都没有进入该功能,我也不明白为什么。
要复制的示例:
package main
import (
"log"
"net/http"
"strconv"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
"github.com/go-playground/validator"
"gopkg.in/guregu/null.v4"
)
type FooStruct struct {
Foo null.Int `json:"foo" binding:"nullIntMin=3"`
}
var validateNullIntMin validator.Func = func(fl validator.FieldLevel) bool {
log.Println("inside validator")
number,ok := fl.Field().Interface().(null.Int)
min := cToInt(fl.Param())
if ok {
if number.Valid && number.Int64 > min {
return false
}
}
return true
}
func cToInt(param string) int64 {
i,64)
panic(err)
return i
}
func main() {
route := gin.Default()
// Custom validator
if v,ok := binding.Validator.Engine().(*validator.Validate); ok {
v.RegisterValidation("nullIntMin",validateNullIntMin)
}
route.POST("/foo",postFoo)
route.Run(":5000")
}
func postFoo(c *gin.Context) {
var f FooStruct
err := c.BindJSON(&f)
if err != nil {
c.JSON(http.StatusBadRequest,gin.H{"status": http.StatusText(http.StatusBadRequest)})
return
}
c.JSON(http.StatusOK,gin.H{"status": http.StatusText(http.StatusOK),"data": f.Foo.Int64})
}
如果您使用
{"foo":1}
您将获得{ “数据”:1, “状态”:“确定” }
当我期望Error:Field validation for 'Foo' failed on the 'nullIntMin' tag
解决方法
您不需要解析验证器中的字段,只需为特殊类型创建自定义大小写即可。
相反,只需创建一个新类型,然后就可以使用常规绑定。
if v,ok := binding.Validator.Engine().(*validator.Validate); ok {
v.RegisterCustomTypeFunc(nullIntValidator,null.Int{})
}
func nullIntValidator(field reflect.Value) interface{} {
if valuer,ok := field.Interface().(null.Int); ok {
if valuer.Valid {
return valuer.Int64
}
}
return nil
}
type FooStruct struct {
Foo null.Int `json:"foo" binding:"min=3"`
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。