Skip to content

Custom error messages and localization #7

@jprochazk

Description

@jprochazk

A rule for custom error messages:

#[derive(Validate)]
struct Test {
    #[garde(required, message="custom message which is actually a format string: {}")]
    a: String,
    #[garde(required, message=custom_message_format)]
    b: String,
    #[garde(required, message=|_: &str, value: &str, _: &()| {
        Ok(format!("custom message in closure: {v}"))
    })]
    c: String,
}

fn custom_message_format(field_name: &str, value: &str, context: &()) -> Result<Cow<'static, str>, Error> {
    Ok(format!("custom message: {value}"))
}

Implementation detail: The string version should differentiate between a const string and a format string. It might make sense to generate a temporary function for format strings which does the actual formatting to enforce encapsulation.

Combined with a custom Context, it should be possible to use this to localize error messages:

struct Locale {
  /*
  - current locale 
  - mapping of (unlocalized -> localized) strings
  */
}

#[derive(Validate)]
#[garde(context(Locale))]
struct User {
  #[garde(length(min=10,max=100), message=|_, v: &str, ctx: &Locale| {
    translate!(ctx, "invalid value {v}")
  })]
  value: String,
}

But it might make sense to support this directly via a translate rule which passes the error message to be further localized - needs some design work.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions