Skip to content

v0.23.0

Latest

Choose a tag to compare

@jprochazk jprochazk released this 23 May 14:49
· 3 commits to main since this release
62b71b1

Internationalization (i18n)

Error messages may now be customized.

struct Czech;

impl I18n for Czech {
    fn length_lower_than(&self, min: usize) -> Cow<'static, str> {
        format!("musí obsahovat alespoň {min} znaků").into()
    }
    
    fn email_invalid(&self, _reason: InvalidEmail) -> Cow<'static, str> {
        format!("email je neplatný").into()
    }
    
    // etc.
}

#[derive(Validate)]
struct User {
    #[garde(length(min = 3))]
    name: String,
    #[garde(email)]
    email: String,
}

let user = User {
    name: "Jan Novák".to_string(),
    email: "invalid-email".to_string(),
};

let result = with_i18n(Czech, || user.validate());

The goal behind this feature is to support localization of error messages, but it can also be used to assign custom error messages in English to all errors produced by garde.

if(cond = <expr>, <rules>...)

Rules may now be nested within an if rule, which only validates if a given condition is true. The condition can refer to self and ctx as with any other rule.

struct Config {
    strict: bool,
}

#[derive(garde::Validate)]
#[garde(context(Config as ctx))]
struct User {
    #[garde(if(cond = ctx.strict, length(min = 8)))]
    username: String,
}

Struct-level custom rules

Custom rules may now be applied to an entire struct. Struct-level and field-level rules may be combined arbitrarily. This is a lightweight alternative to implementing garde::Validate manually.

#[derive(garde::Validate)]
#[garde(custom(foo_is_not_bad))]
struct Foo {
    #[garde(length(min = 8))]
    bar: String,
}

fn foo_is_not_bad(v: &Foo, _: &()) -> garde::Result {
    todo!();
}

Other changes

  • The length rule now works on url::Url (#147).
  • Box<[T]> is now supported as a container, allowing length and inner to be used (#176).
  • Clearer compiler errors when required feature flags are missing (#171).

Bug fixes

  • Deriving Validate on tuple structs with #[garde(skip)] no longer shifts field bindings (#182).
  • Debug for Path now prints the component kind, so path.join("0") and path.join(0) no longer print identically.
  • The main example in the README is now a doctest, and should now actually compile.

Breaking changes

  • Validation traits for credit_card, email, and phone_number no longer have an associated Error type (#150)
  • garde::external was trimmed to only re-export garde::ToCompactString.
  • Some dependencies were updated
  • MSRV is now 1.87.

New Contributors

Full Changelog: v0.22.1...v0.23.0