The data validation component supports the i18n feature, implemented internally using the unified i18n component of the goframe framework. By default, it uses the default i18n singleton object, i.e., the g.I18n() object.

Before further use, please refer to the chapter on configuring and using the i18n internationalization feature: I18N

Configuration Example

Default i18n Error Message

The reference for the default English internationalization language configuration file: https://github.com/gogf/gf/tree/master/util/gvalid/i18n/en

Chinese Error Message

We provide a recommended Chinese i18n internationalization language configuration file: https://github.com/gogf/gf/tree/master/util/gvalid/i18n/cn

Default Error Message

When the corresponding rule’s error message cannot be found in i18n, it will use the error message configured in __default__. This is often used in custom rules.

Development Example

We set the error message i18n language for requests uniformly through middleware.

Directory Structure

Data Validation - Error Msg - 图1warning

Pay attention to the project directory structure so that the default g.i18n() object can automatically read the configuration. A significant number of users stumble here.

  1. ├── main.go
  2. └── i18n
  3. ├── en.toml
  4. └── zh-CN.toml

i18n Files

en.toml

  1. "ReuiredUserName" = "Please input user name"
  2. "ReuiredUserType" = "Please select user type"

zh-CN.toml

  1. "ReuiredUserName" = "请输入用户名称"
  2. "ReuiredUserType" = "请选择用户类型"

Example Code

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "github.com/gogf/gf/v2/i18n/gi18n"
  5. "github.com/gogf/gf/v2/os/gctx"
  6. "github.com/gogf/gf/v2/util/gconv"
  7. )
  8. func main() {
  9. type User struct {
  10. Name string `v:"required#ReuiredUserName"`
  11. Type int `v:"required#ReuiredUserType"`
  12. }
  13. var (
  14. ctx = gctx.New()
  15. data = g.Map{
  16. "name": "john",
  17. }
  18. user = User{}
  19. ctxEn = gi18n.WithLanguage(ctx, "en")
  20. ctxCh = gi18n.WithLanguage(ctx, "zh-CN")
  21. )
  22. if err := gconv.Scan(data, &user); err != nil {
  23. panic(err)
  24. }
  25. // English
  26. if err := g.Validator().Assoc(data).Data(user).Run(ctxEn); err != nil {
  27. g.Dump(err.String())
  28. }
  29. // Chinese
  30. if err := g.Validator().Assoc(data).Data(user).Run(ctxCh); err != nil {
  31. g.Dump(err.String())
  32. }
  33. }

After execution, the terminal output:

  1. Please select user type
  2. 请选择用户类型