Data validation is an important part of software development. It makes sure that input data is accurate and meets the requirements before processing or storing it. In Go, data validation is simple and flexible.
This guide will teach you how to use struct tags to validate data and make your apps safe and reliable. From creating validation logic to using built-in validation tags.
Setting up the Go project dependencies.
go mod init app go get github.com/gin-gonic/gin
├─ main.go ├─ models │ └─ user.go └─ public └─ index.html
The User struct is designed for testing validation within the application, incorporating validation tags to enforce specific rules.
package models type User struct { Id int `binding:"required" msg:"Required"` Name string `binding:"max=10" msg:"Maximum length is 10"` Email string `binding:"email" msg:"Invalid email address"` Age int `binding:"min=1,max=100" msg:"Must between 1 and 100"` BirthDate string `binding:"datetime=01/02/2006" msg:"Invalid date format"` }
Since the default error messages are not user-friendly, we added a custom msg tag to define more meaningful error messages.
This file is the main entry point for our application. It will create and set up the minimal Go web application.
package main import ( "app/models" "net/http" "reflect" "github.com/gin-gonic/gin" "github.com/go-playground/validator/v10" ) func main() { router := gin.Default() router.LoadHTMLFiles("public/index.html") router.GET("/", func(c *gin.Context) { c.HTML(http.StatusOK, "index.html", nil) }) router.POST("/", func(c *gin.Context) { var user models.User if err := c.ShouldBind(&user); err != nil { c.HTML(http.StatusOK, "index.html", gin.H{"User": user, "Errors": getErrors(err, user)}) return } c.HTML(http.StatusOK, "index.html", gin.H{"Pass": true, "User": user}) }) router.Run() } func getErrors(err error, obj any) map[string]string { messages := getMessages(obj) errors := map[string]string{} for _, e := range err.(validator.ValidationErrors) { errors[e.Field()] = messages[e.Field()] } return errors } func getMessages(obj any) map[string]string { t := reflect.TypeOf(obj) messages := map[string]string{} for i := 0; i < t.NumField(); i++ { field := t.Field(i) messages[field.Name] = field.Tag.Get("msg") } return messages }
The HTML user input form is designed to test the validation rules applied to the User struct. It typically includes fields that correspond to the properties of the User struct.
We use Go's HTML template syntax, such as {{if .Errors.Id}}, to display error messages to the user.
go run main.go
Open the web browser and goto http://localhost:8080
You will find this test page.
Click "Fill invalid data" and then click "Submit" to see the error messages displayed in the input form.
Click "Fill valid data" and then "Submit" again. You should see the validation success message displayed in the input form.
This article has covered implementing the basic data validation, helping you build reliable and user-friendly applications. Apply these practices to enhance both the robustness and usability of your Go web application.
Source code: https://github.com/stackpuz/Example-Validation-Go
Create a CRUD Web App in Minutes: https://stackpuz.com
The above is the detailed content of Implement data validation in Go. For more information, please follow other related articles on the PHP Chinese website!