Skip to content

v0.12.0

Compare
Choose a tag to compare
@jprochazk jprochazk released this 27 Jul 19:39
· 190 commits to main since this release

What's Changed

  • removed blanket impls of AsRef<str>, replaced with garde::rules::AsStr
  • removed blanket impls of AsRef<[u8]>, replaced with garde::rules::byte_length::AsByteSlice
  • changed layout of Errors to support inner type validation
  • container-level attributes are now checked for duplicates
  • added #[serde(transparent)] for the Unvalidated newtype
  • added #[garde(required)] for validating Option fields
  • added #[garde(allow_unvalidated)]
  • implemented inner modifier

Handling Option

Every rule works on Option<T> fields. The field will only be validated if it is Some. If you additionally want to validate that the Option<T> field is Some, use the required rule:

#[derive(garde::Validate)]
struct Test {
    #[garde(required, ascii, length(min = 1))]
    value: Option<String>,
}

The above type would fail validation if:

  • value is None
  • the inner value is empty
  • the inner value contains non-ASCII characters

Inner type validation

If you need to validate the "inner" type of a container, such as the String in Vec<String>, then use the inner modifier:

#[derive(garde::Validate)]
struct Test {
    #[garde(
        length(min = 1),
        inner(ascii, length(min = 1)), // wrap the rule in `inner`
    )]
    items: Vec<String>,
}

The above type would fail validation if:

  • the Vec is empty
  • any of the inner String elements is empty
  • any of the inner String elements contains non-ASCII characters

#[garde(allow_unvalidated)]

If most of the fields on your struct are annotated with #[garde(skip)], you may use #[garde(allow_unvalidated)] instead:

#[derive(garde::Validate)]
struct Foo<'a> {
    #[garde(length(min = 1))]
    a: &'a str,

    #[garde(skip)]
    b: &'a str, // this field will not be validated
}

#[derive(garde::Validate)]
#[garde(allow_unvalidated)]
struct Bar<'a> {
    #[garde(length(min = 1))]
    a: &'a str,

    b: &'a str, // this field will not be validated
                // note the lack of `#[garde(skip)]`
}

Full Changelog: v0.11.2...v0.12.0