网站首页 » Beego » Beego 表单中的数据验证

Beego 表单中的数据验证

June 27, 2020 Beego

validation

安装

go get github.com/astaxie/beego/validation

项目中使用:


    userId := c.GetSession("user_info")
    title := c.GetString("title")
    desc := c.GetString("desc")
    tagId := c.GetString("tags_id")

    valid := validation.Validation{}

    type post struct{
        userId string
        title string
        desc string
        tagId string
    }
    //表单验证
    postData := post{userId: strconv.Itoa(userId.(int)), title: title, desc: desc,tagId: tagId}
    valid.Required(postData.userId, "userId").Message("请先登录")
    valid.Required(postData.title, "title").Message("请填写标题")
    valid.MaxSize(postData.title, 20, "title").Message("最多填写20个字符")
    valid.Required(postData.desc,"desc").Message("请填写描述")
    valid.Required(postData.tagId, "tagId").Message("请选择标签")

    if valid.HasErrors() {
        for _, err := range valid.Errors {
            c.Redirect("/jump?status=2&message=" + err.Message, 302)
            return
        }
    }
添加新评论