Skip to content

Templates ​

go
func SetMessageTemplates(templates map[string]string, lang ...language.Tag)

Merge templates into the given locale's template set, overriding any existing entries. The locale defaults to the package default (language.Chinese) when omitted.

Examples ​

Default locale (Chinese) ​

go
govalid.SetMessageTemplates(map[string]string{
    "required": "不能留空",
    "min":      "应当不小于",
})

Specific locale ​

go
govalid.SetMessageTemplates(map[string]string{
    "required": "must not be empty",
}, language.English)

Adding a new locale ​

The locale is created on first call:

go
govalid.SetMessageTemplates(map[string]string{
    "required": " は必須です",
}, language.Japanese)

Diagnostic templates ​

go
govalid.SetMessageTemplates(map[string]string{
    "_checkerNotFound":      "未知的校验规则",
    "_paramError":           "校验规则参数错误",
    "_valueTypeError":       "字段类型不支持该规则",
    "_fieldNotFound":        "引用的字段不存在",
    "_unknownErrorTemplate": "校验失败",
})

Template grammar ​

PatternEffect
Plain string ("不能为空")Prepended with the field label, limit value appended if set
Contains {field} / {limit}Placeholders replaced verbatim
Wrapped in {{ … }}Skip the label prefix and the limit suffix entirely

For examples and edge cases, see Error Messages.

Locale fallback ​

SituationResult
Locale registered, key registeredUse the entry
Locale registered, key missingFall back to _unknownErrorTemplate of that locale
Locale not registeredFall back to the default locale's table

Concurrency ​

SetMessageTemplates is not synchronized. Mutate templates at startup; if you must change them at runtime, do so behind your own mutex with no concurrent Check calls in flight.

Released under the MIT License.