feat ✨: 添加字段验证

This commit is contained in:
wenjianzhang committed 2021-04-08 18:43:17 +08:00
1 parent 221a47423d
commit 14db1e802c
8 files changed
+77 -38

No files matched your search

+2 -2
View File
@@ -27,7 +27,7 @@ func CreateAction(control dto.Control) gin.HandlerFunc {
req := control.Generate()
err = req.Bind(c)
if err != nil {
response.Error(c, http.StatusUnprocessableEntity, err, "参数验证失败")
response.Error(c, http.StatusUnprocessableEntity, err, err.Error())
return
}
var object models.ActiveRecord
@@ -46,4 +46,4 @@ func CreateAction(control dto.Control) gin.HandlerFunc {
response.OK(c, object.GetId(), "创建成功")
c.Next()
}
}
}
+8 -3
View File
@@ -1,6 +1,7 @@
package dto
import (
vd "github.com/bytedance/go-tagexpr/v2/validator"
"net/http"
"github.com/gin-gonic/gin"
@@ -8,8 +9,8 @@ import (
)
type ObjectById struct {
Id int `uri:"id"`
Ids []int `json:"ids"`
Id int `uri:"id" vd:"($>0||len(Ids)$==0)"`
Ids []int `json:"ids" vd:"($==0||len(Ids)$>0)'"`
}
func (s *ObjectById) Bind(ctx *gin.Context) error {
@@ -36,6 +37,10 @@ func (s *ObjectById) Bind(ctx *gin.Context) error {
s.Ids = append(s.Ids, s.Id)
}
}
if err = vd.Validate(s); err != nil {
log.Errorf("Validate error: %s", err.Error())
return err
}
return err
}
@@ -45,4 +50,4 @@ func (s *ObjectById) GetId() interface{} {
return s.Ids
}
return s.Id
}
}