在 GO 中验证 "ozzo-validation"
Validation in GO "ozzo-validation"
我是 GO 的高手 :) 尝试使用 gin
和名为 ozzo-validation
的插件创建简单的 crud
throw it
我的代码:
package models
import (
validation "github.com/go-ozzo/ozzo-validation"
"gorm.io/gorm"
)
type Post struct {
gorm.Model
Name string `gorm:"type:varchar(255);"`
Desc string `gorm:"type:varchar(500);"`
}
type PostData struct {
Name string `json:"name"`
Desc string `json:"desc"`
}
func (p PostData) Validate() error {
return validation.ValidateStruct(&p,
validation.Field(&p.Name, validation.Required, validation.Length(5, 20)),
validation.Field(&p.Desc, validation.Required),
)
}
后控制器:
package controllers
import (
"curd/app/models"
"fmt"
"github.com/gin-gonic/gin"
)
func Store(c *gin.Context) {
// Validate Input
var post models.PostData
err := post.Validate()
fmt.Println(err)
}
{
"name": "sdfsdfsfsdf"
}
问题是一旦我从邮递员提交上述 JSON 数据,验证就会在终端中给我这个:
desc: cannot be blank; name: cannot be blank.
如评论中所述,您需要先将 HTTP 请求中的数据解码为结构,然后才能执行验证。您看到的验证错误是在 Post
结构的新实例(每个字段中的值为零)上调用 Validate()
的产物。试试 this.
func Store(c *gin.Context) {
var post models.PostData
// This will infer what binder to use depending on the content-type header.
if err := c.ShouldBind(&post); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Validate Input
err := post.Validate()
fmt.Println(err)
}
我是 GO 的高手 :) 尝试使用 gin
和名为 ozzo-validation
crud
throw it
我的代码:
package models
import (
validation "github.com/go-ozzo/ozzo-validation"
"gorm.io/gorm"
)
type Post struct {
gorm.Model
Name string `gorm:"type:varchar(255);"`
Desc string `gorm:"type:varchar(500);"`
}
type PostData struct {
Name string `json:"name"`
Desc string `json:"desc"`
}
func (p PostData) Validate() error {
return validation.ValidateStruct(&p,
validation.Field(&p.Name, validation.Required, validation.Length(5, 20)),
validation.Field(&p.Desc, validation.Required),
)
}
后控制器:
package controllers
import (
"curd/app/models"
"fmt"
"github.com/gin-gonic/gin"
)
func Store(c *gin.Context) {
// Validate Input
var post models.PostData
err := post.Validate()
fmt.Println(err)
}
{
"name": "sdfsdfsfsdf"
}
问题是一旦我从邮递员提交上述 JSON 数据,验证就会在终端中给我这个:
desc: cannot be blank; name: cannot be blank.
如评论中所述,您需要先将 HTTP 请求中的数据解码为结构,然后才能执行验证。您看到的验证错误是在 Post
结构的新实例(每个字段中的值为零)上调用 Validate()
的产物。试试 this.
func Store(c *gin.Context) {
var post models.PostData
// This will infer what binder to use depending on the content-type header.
if err := c.ShouldBind(&post); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
return
}
// Validate Input
err := post.Validate()
fmt.Println(err)
}