为了账号安全,请及时绑定邮箱和手机立即绑定

Go gin 验证输入以排除子字符串

Go gin 验证输入以排除子字符串

Go
幕布斯7119047 2022-07-18 16:06:29
我想确保输入不包含子字符串“organization”、“forbidden”并且不等于“foo”和“bar”。// cmd/httpd/handler/item_post.gopackage handlerimport (  "net/http"  "dummy-project/itemdata"  "github.com/gin-gonic/gin")func ItemPost() gin.HandlerFunc {  return func(c *gin.Context) {    requestBody := itemdata.Item{}    if err := c.ShouldBindJSON(&requestBody); err != nil {        c.JSON(http.StatusBadRequest, gin.H{"message": err.Error()})        return    }    // insert Item object to DB    c.JSON(http.StatusCreated, requestBody)  }}下面是我用于 POST 请求和插入数据库记录的结构: // itemdata/item_data.go package itemdata// Item struct used for POST request and inserting new itemtype Item struct {   ID           string `bson:"_id" json:"id"`   Name string `bson:"name" json:"name" binding:"required,excludesrune=organizationforbidden,ne=foo,ne=bar"`}当我插入这些值时: foo -> 排除符文验证失败bar -> ne 上的验证失败组织 -> 排除符文验证失败orgfor -> 排除符文验证失败禁止 -> 排除符文验证失败酒吧 -> 成功我想要什么: foo -> 失败酒吧->失败组织 -> 失败orgfor -> 成功,因为组织和禁止词不完整禁止 -> 失败BAR -> 失败我如何使用 go gin 和 go 验证器来实现这一点?谢谢
查看完整描述

1 回答

?
MM们

TA贡献1886条经验 获得超2个赞

看起来您正在尝试排除整个字符串,因此excludes验证会比excludesrune. Go 中的“符文”是一个 Unicode 代码点,您可能更习惯于仅调用“字符”,因此您的书面验证可能会导致任何包含字母的字符串失败o。


试试这个:


   Name string `bson:"name" json:"name" binding:"required,excludes=organization,excludes=forbidden,ne=foo,ne=bar"`

编辑:如评论中所述,这不符合您禁止使用大写版本的被阻止字符串的要求。据我所知,您需要使用自定义验证器执行此操作:


func caseInsensitiveExcludes(fl validator.FieldLevel) bool {

    lowerValue := strings.ToLower(fl.Field().String())

   

    if strings.Contains(lowerValue, fl.Param()) {

        return false

    }


    return true

}


validate.RegisterValidation("iexcludes", caseInsensitiveExcludes)

然后试试这个字段定义:


   Name string `bson:"name" json:"name" binding:"required,iexcludes=organization,iexcludes=forbidden,ne=foo,ne=bar"`


查看完整回答
反对 回复 2022-07-18
  • 1 回答
  • 0 关注
  • 93 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信