Skip to content

模板

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

templates 合并到指定 locale 的模板集合中,覆盖任何已存在的 条目。省略时使用包默认 locale(language.Chinese)。

示例

默认 locale(中文)

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

指定 locale

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

添加新 locale

locale 在首次调用时会被创建:

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

诊断模板

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

模板语法

模式效果
普通字符串(如 "不能为空"前置字段 label,限制值非 nil 时追加在尾部
包含 {field} / {limit}占位符按字面替换
{{ … }} 包裹完全跳过 label 前缀和限制值后缀

示例与边角情况见 错误消息

locale 回退

情形结果
locale 已注册,键已注册使用该条目
locale 已注册,键缺失回退到该 locale 的 _unknownErrorTemplate
locale 未注册回退到默认 locale 的表

并发

SetMessageTemplates 是同步的。请在启动时改动模板;如果必须 在运行时修改,请用自己的互斥锁包好,并保证没有并发的 Check 在 飞行中。

基于 MIT 协议发布。