form 验证

func (this *AddController) Get() {
this.Data[“form”] = beego.Form(&User{})
this.Layout = “admin/layout.html”
this.TplNames = “admin/add.tpl”
}



https://blog.csdn.net/ma2595162349/article/details/113801792



  1. 数据绑定介绍:
    Gin提供了两类绑定方法:



Must bind:
Methods:
Bind, BindJSON, BindXML, BindQuery, BindYAML
Behavior:
这些方法属于MustBindWith的具体调用. 如果发生绑定错误, 则请求终止, 并触发 c.AbortWithError(400, err).SetType(ErrorTypeBind)响应状态码被设置为 400 并且Content-Type被设置为text/plain; charset=utf-8. 如果您在此之后尝试设置响应状态码, Gin会输出日志[GIN-debug] [WARNING] Headers were already written. Wanted to override status code 400 with 422. 如果您希望更好地控制绑定, 考虑使用ShouldBind等效方法.
Should bind:
Methods:
ShouldBind, ShouldBindJSON, ShouldBindXML, ShouldBindQuery, ShouldBindYAML
Behavior:
这些方法属于ShouldBindWith的具体调用. 如果发生绑定错误, Gin 会返回错误并由开发者处理错误和请求.



数据绑定–Must bind
3.1 Bind
可以绑定Form、QueryString、Json等



和ShouldBind的区别在于,ShouldBind没有绑定成功不报错,就是空值,Bind会报错



3.2 BindQuery等
BindJSON, BindXML, BindQuery, BindYAML等函数只绑定对应格式的参数



二、数据验证:



  1. 使用:
    go-playground/validator.v8进行验证



https://blog.csdn.net/qq_35709559/article/details/109481269



https://github.com/gin-gonic/gin/issues/1052#issuecomment-515966643



https://echo.labstack.com/guide/binding/#form-data



https://github.com/labstack/echox/blob/master/website/content/guide/binding.md



https://github.com/go-playground/validator



form:"field_name,default=value"



https://github.com/go-playground/form



https://blog.csdn.net/hellozhxy/article/details/123778868



用户自定义函数验证



用户自定义函数验证字段是否合法,效验是否正确。



例子3: 通过字段tag自定义函数



validate.RegisterValidation



validate = validator.New()
validate.RegisterValidation(“CustomerValidation”, CustomerValidationFunc) //注册自定义函数,前一个参数是struct里tag自定义,后一个参数是自定义的函数



user := &User{
Name: "jimmy",
Age: 86,
}

fmt.Println("first value: ", user)
err := validate.Struct(user)


https://www.jb51.net/article/197506.htm



Category golang