Implement data validation in Go

WBOY
Release: 2024-08-19 12:31:20
Original
582 people have browsed it

Implement data validation in Go

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.

Prerequisites

  • Go 1.21

Setup project

Setting up the Go project dependencies.

go mod init app go get github.com/gin-gonic/gin
Copy after login

Project structure

├─ main.go ├─ models │ └─ user.go └─ public └─ index.html
Copy after login

Project files

user.go

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"` }
Copy after login

Since the default error messages are not user-friendly, we added a custom msg tag to define more meaningful error messages.

main.go

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 }
Copy after login
  • GET method to return the input form.
  • POST method for form submission and validation of user input.
  • getErrors() returns the error information.
  • getMessages() leverages our custom msg tag to retrieve error messages for specific fields.

index.html

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.

       
  
{{if .Errors.Id}}{{.Errors.Id}}{{end}}
{{if .Errors.Name}}{{.Errors.Name}}{{end}}
{{if .Errors.Email}}{{.Errors.Email}}{{end}}
{{if .Errors.Age}}{{.Errors.Age}}{{end}}
{{if .Errors.BirthDate}}{{.Errors.BirthDate}}{{end}}
{{if .Pass}}
Validation success!
{{end}}
Copy after login

We use Go's HTML template syntax, such as {{if .Errors.Id}}, to display error messages to the user.

Run project

go run main.go
Copy after login

Open the web browser and goto http://localhost:8080

You will find this test page.

Implement data validation in Go

Testing

Click "Fill invalid data" and then click "Submit" to see the error messages displayed in the input form.

Implement data validation in Go

Click "Fill valid data" and then "Submit" again. You should see the validation success message displayed in the input form.

Implement data validation in Go

Conclusion

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!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!