Skip to content

Error Messages

govalid's error system is designed to be useful out of the box and trivial to override. Every failing rule produces an *ErrContext whose Error() returns a human-readable string composed from three pieces:

  1. The field's label (e.g. "邮箱")
  2. The rule's template (e.g. "不能为空")
  3. The rule's limit value, if any (e.g. 100 for max:100)

For example: min:0 on a label "评分" produces "评分应大于0".

Field-level overrides via msg

The simplest way to change a message is the msg tag on a struct field. The first failing rule short-circuits to that text:

go
type Form struct {
    Password string `valid:"required;minlen:8;maxlen:64" label:"密码" msg:"密码长度需在 8-64 之间"`
}

Use msg when product copy is more important than fine-grained reasons.

Replacing rule templates

SetMessageTemplates merges your overrides into a locale's template set. The default locale is Chinese; pass a language.Tag to update a different one:

go
govalid.SetMessageTemplates(map[string]string{
    "required": "can not be null",
    "min":      "must be greater than",
})

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

Template anatomy

A template can carry placeholders or be wrapped in {{ … }}:

PatternEffect
Plain string ("不能为空")Prepended with the field label, limit value appended if non-nil
Contains {field} / {limit}Placeholders are replaced verbatim
Wrapped in {{ … }}Skip the label prefix and the limit suffix entirely
go
govalid.SetMessageTemplates(map[string]string{
    "min": "{{字段 {field} 必须 ≥ {limit}}}",
})

// → "字段 Score 必须 ≥ 10"  (no label prefix, no limit suffix)

The placeholder constants FieldNamePlaceholder = "{field}" and FieldLimitPlaceholder = "{limit}" are exported, so you can reference them programmatically if you build templates from configuration.

Diagnostic templates

govalid uses three internal templates for diagnostic situations. They all start with _:

KeyUsed when
_checkerNotFoundTag references a checker that isn't registered
_unknownErrorTemplateCustom checker hits an unmapped key
_paramErrorTag parameters are missing/malformed
_valueTypeErrorRuntime kind isn't supported by the checker
_fieldNotFoundCross-field rule references a non-existent field

Override them just like regular rules:

go
govalid.SetMessageTemplates(map[string]string{
    "_checkerNotFound": "未知的校验规则",
})

Programmatic access

Each entry in the returned errs slice is an *ErrContext whose public fields you can introspect:

go
errs, ok := govalid.Check(form)
if !ok {
    for _, e := range errs {
        log.Printf("[%s] label=%q value=%v -> %s",
            e.FieldName, e.FieldLabel, e.FieldValue, e)
    }
}

Mutating an error after the fact

*ErrContext exposes two mutators if you need to tweak the message post-hoc — typically inside a custom checker:

go
ctx := govalid.NewErrorContext(c)
ctx.SetTemplate("alphadash") // swap to a different template entirely
ctx.SetFieldLimitValue(42)   // re-render with a new limit value

SetTemplate clears any previously stored limit value, so messages like "name can not be empty<old limit>" can never leak across templates.

Released under the MIT License.