Skip to main content

rustapi_validate/v2/
i18n.rs

1#[cfg(feature = "i18n")]
2use rust_i18n::t;
3
4/// Helper to translate a message.
5///
6/// Falls back to the message key if no translation is found.
7///
8/// # Arguments
9///
10/// * `key` - The message key (e.g. "validation.email.invalid")
11/// * `locale` - The locale to use (e.g. "en", "tr"). If None, uses default.
12pub fn translate(key: &str, locale: Option<&str>) -> String {
13    #[cfg(feature = "i18n")]
14    {
15        let result = if let Some(locale) = locale {
16            t!(key, locale = locale).to_string()
17        } else {
18            t!(key).to_string()
19        };
20
21        if result == key {
22            t!(key, locale = "en").to_string()
23        } else {
24            result
25        }
26    }
27
28    #[cfg(not(feature = "i18n"))]
29    {
30        let _ = locale;
31        fallback_message(key)
32    }
33}
34
35/// Helper to translate with arguments.
36pub fn translate_with_args(key: &str, locale: Option<&str>, _args: &[(&str, &str)]) -> String {
37    translate(key, locale)
38}
39
40#[cfg(not(feature = "i18n"))]
41fn fallback_message(key: &str) -> String {
42    match key {
43        "validation.email.invalid" => "Invalid email format",
44        "validation.length.min" => "Length must be at least %{min} characters",
45        "validation.length.max" => "Length must be at most %{max} characters",
46        "validation.length.exact" => "Length must be exactly %{len} characters",
47        "validation.range.min" => "Value must be at least %{min}",
48        "validation.range.max" => "Value must be at most %{max}",
49        "validation.range.between" => "Value must be between %{min} and %{max}",
50        "validation.required.missing" => "This field is required",
51        "validation.url.invalid" => "Invalid URL format",
52        "validation.regex.mismatch" => "Value does not match pattern: %{pattern}",
53        "validation.unique.taken" => "This value is already taken",
54        "validation.exists.not_found" => "Value does not exist",
55        "validation.api.invalid" => "External validation failed",
56        "validation.credit_card.invalid_format" => "Invalid credit card format",
57        "validation.credit_card.invalid" => "Invalid credit card number",
58        "validation.ip.v4_required" => "IPv4 address required",
59        "validation.ip.v6_required" => "IPv6 address required",
60        "validation.ip.invalid" => "Invalid IP address",
61        "validation.phone.invalid" => "Invalid phone number",
62        "validation.contains.missing" => "Required value is missing",
63        other => other,
64    }
65    .to_string()
66}