Skip to content

Instantly share code, notes, and snippets.

@wadtech
Last active November 12, 2018 14:35
Show Gist options
  • Save wadtech/c8a62a42a0ff618aa95f4c0b854b52f6 to your computer and use it in GitHub Desktop.
Save wadtech/c8a62a42a0ff618aa95f4c0b854b52f6 to your computer and use it in GitHub Desktop.
Using govalidator custom validation messages to implement i18n

This example uses the LANG env var so these commands set it as courtesy.

LANG=zh_CN.UTF-8 go run main.go
格式错误
LANG=en_GB.UTF-8 go run main.go
Invalid email address
package main
import (
"fmt"
"os"
"github.com/asaskevich/govalidator"
// my pretend module with some translation logic
"github.com/my/translations"
)
type person struct {
Name string `valid:"-"`
Email string `valid:"email~EMAIL_INVALID"` // email is not correct || email 格式错误
}
func main() {
translations.SetLocale("en_GB.UTF-8")
p := person{Name: "clearcodecdn", Email: "jjj"}
_, err := govalidator.ValidateStruct(p)
if err != nil {
localeAwareText := translations.Translate(err.Error())
fmt.Println(localeAwareText)
return
}
// no validation errors
fmt.Println("All OK")
}
package translations
import (
"github.com/my/translations/en_gb"
"github.com/my/translations/zh_CN"
)
var locale string
func SetLocale(myLocale string) {
// checked against some whitelist
locale = myLocale
}
func Translate(myStr string) (string, ok) {
if locale == "en_GB.UTF-8" {
// the particular translations could come from a file, a database, an API or whatever.
translation, ok := en_gb.Lookup(myStr)
}
// etc, or a switch or something
return translation, ok
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment