Translations
Every message is a template from a JSON catalog, filled from the issue's parameters. The default English messages come from en.json and need no feature. With the i18n feature vld embeds the English, Russian, German and Spanish catalogs (add more with i18n-<lang> features, below) and translates through i18n-next: CLDR plural rules, fallback chains, app overrides.
vld = { version = "…", features = ["i18n"] } # en, ru, de, es
vld = { version = "…", features = ["i18n", "i18n-fr", "i18n-ja"] } # + French, Japanese
vld = { version = "…", features = ["i18n-all"] } # all 29
Only the catalogs of enabled features are compiled into the binary (about 16 KiB each); the rest stay out. I18N_NEXT_LOCALES trims i18n-next's own CLDR data, not vld's catalogs.
use vld::prelude::*;
use vld::i18n::{translate_error, translator};
let err = vld::string().len(3).parse(r#""ab""#).unwrap_err();
let ru = translate_error(&err, &translator("ru-RU"));
assert_eq!(ru.issues[0].message, "Строка должна содержать ровно 3 символа");
translator(locale) takes any language tag: pt-BR reads pt, zh_Hans_CN reads zh, a key missing in a catalog and a language whose catalog is not embedded read English. vld::i18n::supported_locale(tag) tells which catalog a tag gets (None: English).
Languages
| Code | Language | Plural forms | Code | Language | Plural forms |
|---|---|---|---|---|---|
ar | Arabic | one, two, few, many, other | id | Indonesian | other |
bg | Bulgarian | one, other | it | Italian | one, other |
cs | Czech | one, few, other | ja | Japanese | other |
da | Danish | one, other | ko | Korean | other |
de | German | one, other | nb | Norwegian Bokmål (no) | one, other |
el | Greek | one, other | nl | Dutch | one, other |
en | English | one, other | pl | Polish | one, few, many |
es | Spanish | one, other | pt | Portuguese | one, other |
fi | Finnish | one, other | ro | Romanian | one, few, other |
fr | French | one (0 and 1), other | ru | Russian | one, few, many |
he | Hebrew (iw) | one, two, other | sv | Swedish | one, other |
hi | Hindi | one (0 and 1), other | th | Thai | other |
hu | Hungarian | one, other | tr | Turkish | one, other |
uk | Ukrainian | one, few, many | |||
vi | Vietnamese | other | |||
zh | Chinese (Simplified) | other |
Feature per language: i18n-<code> (i18n-fr, i18n-zh, …); de, en, es, ru come with i18n itself. vld::i18n::locales() lists the embedded codes, vld::i18n::catalog("ru") returns an embedded catalog's JSON; every file is also in the repository's crates/vld/locales/ for a frontend.
Catalog format
The files are crates/vld/locales/{locale}.json: one flat object, keys vld.<message key> (the keys of IssueCode::message_keys()) and vld.type.<type> (the type names of invalid_type).
{
"vld.invalid_type": "Ожидался тип «{expected}», получен «{received}»",
"vld.type.string": "строка",
"vld.invalid_string.email": "Некорректный адрес электронной почты",
"vld.invalid_length.string": "=0 Строка должна содержать ровно {expected} символов | Строка должна содержать ровно {expected} символ | Строка должна содержать ровно {expected} символа | Строка должна содержать ровно {expected} символов",
"vld.union_variant": "[вариант {n}]"
}
{name}is a parameter of the issue code ({minimum},{expected},{network}, …); every language uses English's placeholders.- Size messages are i18n-next plurals:
=0+ the form for 0, then one form per CLDR category the language's whole numbers reach, in the order zero, one, two, few, many, other (en:=0 … | one | other,ru:=0 … | one | few | many,ar:=0 … | one | two | few | many | other). A language with one category (ja,zh, …) has a single form without|. - Specific keys fall back to their generic key (
too_small.tuple→too_small), so a catalog has only the keys English has.
Your app's catalog: override keys, add a language
An app on i18n-next loads vld's files as a library layer with Builder::extend; its own files and messages go over them. Translator::new(view) translates with that catalog:
use vld::i18n::{Translator, files, translate_error, i18n_next::I18n};
let i18n = I18n::builder()
.extend(files()) // vld's catalogs, under the app's
.dir("locales") // the app's own locales/{locale}.json
.locale("ru")
.fallback("en")
.build()?;
let messages = Translator::new(i18n.with_locale("ru")); // or i18n.page("index"): the active locale
let ru = translate_error(&err, &messages);
- Override a message: put the key in the app's
locales/ru.json, e.g."vld.invalid_string.email": "Проверьте адрес почты". Withextend, the order is the app'sru, vld'sru, then the fallback chain. - Add a language: give
locales/eo.jsonthevld.*keys you want ("vld.missing_field": "Mankas deviga kampo"); the rest comes from the app's fallback chain. i18n-next picks the plural forms by the language's CLDR rules. - Translate your own codes: a
Customcode (refine, rules,custom) is looked up asvld.<code>, e.g."vld.no_spaces": "Пробелы не допускаются". - Without
extend,Translator::newstill falls back to the embedded catalog of the view's locale when the app has no such key.
vld re-exports its i18n-next as vld::i18n::i18n_next; an app that depends on i18n-next directly needs the same minor (0.2).
Frontend
The catalogs are plain locale files of nuxt-i18n-micro / i18n-next: a frontend translates the code and params of an issue (the serialized VldError, the Tauri TauriIssue { code, params }, a vld-web error body) with the same strings.
Export them next to the frontend's own files (a build script or a one-off command):
for locale in vld::i18n::locales() {
std::fs::write(format!("locales/vld/{locale}.json"), vld::i18n::catalog(locale).unwrap())?;
}
or copy crates/vld/locales/*.json from the vld source. Then merge them into the app's messages and look up the issue's most specific key first:
// Vue / React with @i18n-micro: issue = { code, params, message } (TauriIssue, a serialized issue)
function issueMessage(i18n, { code, params, message }) {
const base = params.inclusive === 'false' ? `${code}_exclusive` : code
const sub = params.origin ?? params.validation ?? params.format ?? params.kind
const p = { ...params }
if (code === 'invalid_type') {
for (const k of ['expected', 'received'])
if (i18n.has(`vld.type.${p[k]}`)) p[k] = i18n.t(`vld.type.${p[k]}`)
}
for (const key of sub ? [`${base}.${sub}`, base] : [base]) {
if (!i18n.has(`vld.${key}`)) continue
const count = Number(params.minimum ?? params.maximum ?? params.expected)
return Number.isInteger(count) ? i18n.tc(`vld.${key}`, count, p) : i18n.t(`vld.${key}`, p)
}
return message
}
- Tauri: with
tauri-plugin-i18n-next, build the RustI18nwith.extend(vld::i18n::files()); the WebView then receives thevld.*keys with the rest of the catalog, and Rust commands can translate withTranslator::new(i18n.page("index")). - Leptos / any Rust wasm frontend: enable
vld/i18nand calltranslator(locale), orTranslator::newover the app's i18n-next instance. The catalogs are embedded, nothing is fetched.
Other sources: MapResolver, FnResolver
Without the feature, or for Fluent, gettext or a database, implement MessageResolver or use the two helpers. MapResolver wraps a HashMap<String, String> of templates:
use std::collections::HashMap;
use vld::i18n::{translate_error, MapResolver};
let mut t = HashMap::new();
t.insert("too_small.string".into(), "Mínimo {minimum} caracteres".into());
t.insert("invalid_string.email".into(), "Correo no válido".into());
let resolver = MapResolver::new(t);
let err = vld::string().min(5).email().parse(r#""ab""#).unwrap_err();
let es = translate_error(&err, &resolver);
assert_eq!(es.issues[0].message, "Mínimo 5 caracteres");
english() returns a MapResolver with every default template (a plural message as key and key_one), a base for overriding a few keys.
FnResolver takes a closure:
use vld::i18n::{translate_error, FnResolver};
let resolver = FnResolver::new(|key| match key {
"too_small" => Some("Zu kurz! Mindestens {minimum} Zeichen.".into()),
_ => None,
});
let de = translate_error(&err, &resolver);
MessageResolver has resolve(key), plus resolve_count(key, n) for size messages and plural_category(n). By default a size message with an integer bound tries <key>_<category> first (too_small.string_one, …_few), then <key>; set the rule with MapResolver::with_plural_rule(fn(u64) -> &'static str).
Lookup order
For each issue the resolver is asked for the keys of IssueCode::message_keys(), most specific first (too_small.string, then too_small). The first template found wins; with no match the message is unchanged. Exclusive bounds use too_small_exclusive / too_big_exclusive, so an "at least" template is never applied to a "greater than" check. A union's [variant N] prefix is translated through union_variant. invalid_type translates its {expected} / {received} through type.<name>.
Custom messages are kept
An issue whose message is not the default English one (from _msg builders, with_messages, .message(), type_error(), refine, …) is returned unchanged by translate_error.