Validating fields in a struct is a frequent case in daily development, fortunately, Golang has provided an excellent package named validator to help us accomplish this task. At first, we download the validator:
go get gopkg.in/go-playground/validator.v9
Assume that we need to validate every user that's entering our website now, we can do as such:
package main
import (
"fmt"
"gopkg.in/go-playground/validator.v9"
)
type User struct {
Name string `json:"firstname" validate:"required"`
Address string `json:"lastname" validate:"omitempty"`
Age string `json:"username" validate:"required,gte=18"`
Password string `json:"password" validate:"required,gte=8"`
}
func main() {
user := User{
Name: "tom",
Address: "Beijing, district chaoyang",
}
validate := validator.New()
err := validate.Struct(user)
if err != nil {
fmt.Println(err)
return
}
fmt.Println("Success")
}
The code above will generate output as follows:
Key: 'User.Age' Error:Field validation for 'Age' failed on the 'required' tag
Key: 'User.Password' Error:Field validation for 'Password' failed on the 'required' tag
If we change the user value to satisfy the validate tag defined in User Struct,
user := User{
Name: "tom",
Address: "Beijing, district chaoyang",
Age: 20,
Password: "0123456789",
}
Then we can get the output:
Success
All of the tags that can be used can be found in this page: pkg.go.dev/github.com/…