Validating your first HTML form
Most of the time, we have to validate a client's input before processing it, which can be achieved through the number of external packages in Go, such as gopkg.in/go-playground/validator.v9
, gopkg.in/validator.v2
, and github.com/asaskevich/govalidator
.
In this recipe, we will be working with the most famous and commonly used validator, github.com/asaskevich/govalidator
, to validate our HTML form.
Getting ready…
As we have already created and read an HTML form in our previous recipe, we will just extend it to validate its field values.
How to do it…
- Install
github.com/asaskevich/govalidator
and thegithub.com/gorilla/schema
package using thego get
command, as follows:
$ go get github.com/asaskevich/govalidator
$ go get github.com/gorilla/schema
- Create
html-form-validation.go
, where we will read an HTML form, decode it usinggithub.com/gorilla/schema
, and validate each field of it against a tag defined in theUser struct
usinggithub.com/asaskevich/govalidator
,...