验证器结构
type RegisterValidator struct {
Name string `form:"name" json:"name" binding:"required,min=4,max=50"`
Email string `form:"email" json:"email" binding:"required,email,min=4,max=50"`
Password string `form:"password" json:"password" binding:"required,min=8,max=50"`
MobileCountryCode int `form:"mobile_country_code" json:"mobile_country_code" binding:"required,gte=2,lt=5"`
Mobile int `form:"mobile" json:"mobile" binding:"required,gte=5,lt=15"`
UserModel users.User `json:"-"`
}
设置自定义错误的格式,如下所示:
type CustomError struct {
Errors map[string]interface{} `json:"errors"`
}
func NewValidatorError(err error) CustomError {
res := CustomError{}
res.Errors = make(map[string]interface{})
errs := err.(validator.ValidationErrors)
for _, v := range errs {
param := v.Param()
field := v.Field()
tag := v.Tag()
if param != "" {
res.Errors[field] = fmt.Sprintf("{%v: %v}", tag, param)
} else {
res.Errors[field] = fmt.Sprintf("{key: %v}", tag)
}
}
return res
}
当发送的数据是
{
"email": "me@example.com",
"name": "John Doe",
"mobile_country_code": 1,
"mobile": 1234567
}
但发送无效类型
{
"email": "me@example.com",
"name": "John Doe",
"mobile_country_code": "1",
"mobile": 1234567
}
抛出错误interface conversion: error is *json.UnmarshalTypeError, not validator.ValidationErrors
这个问题与此问题有关:如何断言错误类型 json。当被杜松子酒c.BindJSON捕获时,取消消息打印错误,但是答案没有意义。
慕桂英3389331
米脂
相关分类