gin-gonic / gin

Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.
https://gin-gonic.com/
MIT License
78.88k stars 8.02k forks source link

Golang / Gin Form Field Validation with ShouldBindWith #1257

Closed cxk280 closed 6 years ago

cxk280 commented 6 years ago

I am passing HTML form to data to a controller in Go. I am working off boilerplate to teach myself Go, and it includes form validation. The relevant statement, already changed somewhat from its original appearance in the boilerplate, is below:

if err := c.ShouldBindWith(&signinForm, binding.Form); err != nil {
      log.Println("err: ",err)
      c.JSON(406, gin.H{"message": "Invalid signin form", "form": signinForm})
      c.Abort()
      return
  }

The err logs as Key: 'SigninForm.Email' Error:Field validation for 'Email' failed on the 'email' tag.

In particular, I don't really know what c.ShouldBindWith(&signinForm, binding.Form) does (it was suggested by someone else in regards to my previous issue with signinForm being empty, which it solved).

How do I properly validate the form fields so that err == nil?

cxk280 commented 6 years ago

I resolved this. It turns out that ShouldBindWith is in fact doing validation, and any errors I am seeing are coming from a different place in my code.