Validation 如何从gin绑定/验证中获取有错误的字段?
我有以下代码:Validation 如何从gin绑定/验证中获取有错误的字段?,validation,go,go-gin,Validation,Go,Go Gin,我有以下代码: package main import ( "fmt" "github.com/gin-gonic/gin" ) type TestForm struct { Age int `form:"age" binding:"required"` Name string `form:"name" binding:"required"` } func home(c *gin.Context) { c.HTML(200, "index.h
package main
import (
"fmt"
"github.com/gin-gonic/gin"
)
type TestForm struct {
Age int `form:"age" binding:"required"`
Name string `form:"name" binding:"required"`
}
func home(c *gin.Context) {
c.HTML(200, "index.html", nil)
}
func homePost(c *gin.Context) {
var f TestForm
err := c.Bind(&f)
c.String(200, fmt.Sprintf("%v : %v", err, f))
}
func main() {
r := gin.Default()
r.LoadHTMLGlob("templates/*")
r.Use(gin.Recovery())
r.GET("/", home)
r.POST("/", homePost)
r.Run()
}
和模板/index.html:
<!doctype html>
<html>
<head></head>
<body>
<h1>hello</h1>
<form action="/" method="POST">
<input type="text" name="name">
<input type="text" name="age">
<input type="submit">
</form>
</body>
</html>
我发现从err:=c.Bind(&f)
返回的err
是类型validator.ValidationErrors
,它允许我完全这样做,到目前为止一切都很好
但是,如果我输入test作为name
和abc
作为age`(或者只输入一个后面有空格的数字),则响应如下:
Key: 'TestForm.Age' Error:Field validation for 'Age' failed on the 'required' tag : {0 asd}
strconv.ParseInt: parsing "abc": invalid syntax : {0 }
所以,这只是一个一般性错误,某个地方无法解析整数
现在我无法知道哪个字段失败了,也无法获得任何关于其他字段未通过验证的信息。有没有办法让gin告诉我,在这种情况下,
age
字段失败了?这就是Bind
的工作原理,好的错误来自验证,只有在绑定成功完成后才会发生。如果Bind
无法将值设置为字段(例如,字符串“abc”
设置为int
字段),则它将返回一个错误,而不会调用验证。只有在绑定已设置字段时才能进行验证。。。一种解决方法是使用ShouldBind
而不是Bind
,ShouldBindXxx
方法组会将错误返回给您,而不是像Bind
那样只响应400
。。。。但是您必须做一些手工工作,您必须将ParseInt
错误转化为可以在html模板中使用的内容。如何做到这一点取决于您。好的,是否有其他框架提供更友好的绑定和验证支持,以便更容易地通知用户他们在哪个领域搞错了-而不必在前端完成所有工作?我不知道,可能有,但我不知道,所以你必须自己研究。@binary01你找到这个问题的解决方案了吗?