-
Notifications
You must be signed in to change notification settings - Fork 43
Open
Labels
enhancementNew feature or requestNew feature or request
Milestone
Description
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.
Reactions are currently unavailable
Metadata
Metadata
Assignees
Labels
enhancementNew feature or requestNew feature or request