SoFunction
Updated on 2025-03-04

Go language combined with validator package to implement form verification

In modern web development, form verification and error handling are crucial links, especially in multi-language environments.

This article will use a practical example to demonstrate how to use the Gin framework in Go languagevalidatorpackage, implements advanced form verification functions, and supports internationalized (i18n) error message prompts.

Background and requirements

Suppose we are developing a user registration function that requires strict verification of the information submitted by the user. For example, the user name cannot be empty, the mailbox format must be correct, the password and confirmation password must be consistent, the user's age should be within a reasonable range (such as 1 to 130 years old), and the date field cannot be earlier than the current date. In addition, the system also needs to provide error prompt information for the corresponding language based on the user's language preferences.

Code Example

We will develop from the following aspects:

  • Structure definition of form data
  • Initialization and customization of form validator
  • Implementation of multilingual support
  • Process form submission and error return
package main

import (
	"fmt"
	"net/http"
	"reflect"
	"strings"
	"time"

	"/gin-gonic/gin"
	"/gin-gonic/gin/binding"
	"/go-playground/locales/en"
	"/go-playground/locales/zh"
	ut "/go-playground/universal-translator"
	"/go-playground/validator/v10"
	enTranslations "/go-playground/validator/v10/translations/en"
	zhTranslations "/go-playground/validator/v10/translations/zh"
)

// Define a global translatorvar trans 

Form data structure definition

First, we define the form data structure submitted by the userSignUpParam. This structure contains the fields required for user registration, and validation rules are specified through the structure tags.

type SignUpParam struct {
	Age        uint8  `json:"age" binding:"gte=1,lte=130"`
	Name       string `json:"name" binding:"required"`
	Email      string `json:"email" binding:"required,email"`
	Password   string `json:"password" binding:"required"`
	RePassword string `json:"re_password" binding:"required,eqfield=Password"`
	Date       string `json:"date" binding:"required,datetime=2006-01-02,checkDate"`
}
  • AgeFields must be between 1 and 130 years old.
  • NameThe field cannot be empty.
  • EmailThe field must be a valid email address.
  • PasswordandRePasswordThe fields must be consistent.
  • DateThe fields need to use a custom verification methodcheckDate, make sure that the input date is later than the current date.

Initialize and customize form validators

In the Gin framework, we can()Get the built-in validator and customize it.

In the following code, we completed the initialization of the translator and registered a custom tag name and verification method.

func InitTrans(locale string) (err error) {
	if v, ok := ().(*); ok {

		// Register custom method to get JSON tags		(func(fld ) string {
			name := (("json"), ",", 2)[0]
			if name == "-" {
				return ""
			}
			return name
		})

		// Register structure-level verification function		(SignUpParamStructLevelValidation, SignUpParam{})

		// Register custom verification method		if err := ("checkDate", customFunc); err != nil {
			return err
		}

		// Initialize multilingual support		zhT := () 
		enT := ()
		uni := (enT, zhT, enT)

                var ok bool
		trans, ok = (locale)
		if !ok {
			return ("(%s) failed", locale)
		}

		// Register language translation		switch locale {
		case "en":
			err = (v, trans)
		case "zh":
			err = (v, trans)
		default:
			err = (v, trans)
		}
		if err != nil {
			return err
		}

		// Register custom translation		if err := (
			"checkDate",
			trans,
			registerTranslator("checkDate", "{0}Must be later than the current date"),
			translate,
		); err != nil {
			return err
		}
		return
	}
	return
}

Implement custom verification logic

In the above code, we customize two check functions:

  • customFunc: Used to check whether the date is later than the current date.
  • SignUpParamStructLevelValidation: Used to verify whether the two password fields are consistent.
func customFunc(fl ) bool {
	date, err := ("2006-01-02", ().String())
	if err != nil {
		return false
	}
	return (())
}

func SignUpParamStructLevelValidation(sl ) {
	su := ().Interface().(SignUpParam)
	if  !=  {
		(, "re_password", "RePassword", "eqfield", "password")
	}
}

Handle multilingual error prompts

To ensure that the error message can be returned correctly according to the user's language preferences, we have registered a custom translation functionregisterTranslator, and use this function to translate the error message when verification fails.

// registerTranslator adds translation function to custom fieldsfunc registerTranslator(tag string, msg string)  {
	return func(trans ) error {
		if err := (tag, msg, false); err != nil {
			return err
		}
		return nil
	}
}

// translate custom fields translation methodfunc translate(trans , fe ) string {
	msg, err := ((), ())
	if err != nil {
		panic(fe.(error).Error())
	}
	return msg
}

Main program logic

Finally, we process the user's registration request in Gin. When the data submitted by the user fails to be validated, the system will automatically return the translated error message.

// removeTopStruct Remove the structure name identifier in the field name// refer from:/go-playground/validator/issues/633#issuecomment-654382345
func removeTopStruct(fields map[string]string) map[string]string {
	res := map[string]string{}
	for field, err := range fields {
		res[field[(field, ".")+1:]] = err
	}
	return res
}

func main() {
	// Initialize the translator	if err := InitTrans("zh"); err != nil {
		("Initialization of the translator failed: %v\n", err)
		return
	}

	r := ()

	("/signup", func(c *) {
		var u SignUpParam
		if err := (&u); err != nil {
			errs, ok := err.()
			if !ok {
				(, {"msg": ()})
				return
			}
			(, {"msg": removeTopStruct((trans))})
			return
		}

		// Some other business logic operations...
		(, {"msg": "success"})
	})

	err := (":8080")
	if err != nil {
		("Server failed to run: %v\n", err)
	}
}

Summarize

This article uses a complete example to show how to implement multilingual form validation using the Gin framework in Go.

We not only explore the basic verification rules, but also introduce how to customize the verification logic and how to achieve internationalization error prompts. This method makes our applications more powerful not only in terms of functionality, but also better adapt to global needs.

This is the article about the implementation of form verification by combining Go language with validator package. For more relevant Go validator form verification content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!