gin 框架 ShouldBind 方法 绑定验证出错

问题描述

从html前台post表单到gin后台,数据丢失没有绑定成功

html前台代码

<form action="/register" method="POST" class="margin-bottom-0">
    <label class="control-label">Name</label>
    <div class="row m-b-15">
        <div class="col-md-12">
            <input type="text" name="name" class="form-control" placeholder="User Name" />
        </div>
    </div>
    <label class="control-label">Email</label>
    <div class="row m-b-15">
        <div class="col-md-12">
            <input type="email" name="email" class="form-control" placeholder="Email address" />
        </div>
    </div>
    <label class="control-label">Password</label>
    <div class="row m-b-15">
        <div class="col-md-12">
            <input type="password" name="password" class="form-control" placeholder="Password" />
        </div>
    </div>
    <label class="control-label">Password Confirmation</label>
    <div class="row m-b-15">
        <div class="col-md-12">
            <input type="password" name="password_confirmation" class="form-control" placeholder="Password Confirmation" />
        </div>
    </div>
    <div class="register-buttons">
        <button type="submit" class="btn btn-info btn-block btn-lg">Sign Up</button>
    </div>
</form>

Gin路由

router.GET("/register",auth.ShowRegistrationForm)
router.POST("/register",auth.Register)

Form struct

type RegisterForm struct {
    Name                 string `form:"name" binding:"required"`
    Email                string `form:"email" binding:"required"`
    Password             string `form:"password" binding:"required"`
    PasswordConfirmation string `from:"password_confirmation" binding:"required"`
}

Gin Controller

func Register(c *gin.Context) {
    var data RegisterForm
    if err := c.ShouldBind(&data); err != nil {
        c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
        return
    }

    c.JSON(http.StatusOK, gin.H{
        "data": data,
    })
}

报错信息

{
    "error": "Key: 'RegisterForm.PasswordConfirmation' Error:Field validation for 'PasswordConfirmation' failed on the 'required' tag"
}

有人遇到这个问题吗?

gin
讨论数量: 2

难道不是 password_confirmation required (必填) 的问题?

4年前 评论

问题已经解决,是自己大意了把form写成了from

4年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!