facet-validate

facet-validate adds field validation to the facet deserialization pipeline. Validators run during deserialization, so errors carry the source span pointing to the exact location in the input (e.g. the offending JSON field) rather than surfacing after the fact.

rust
use facet::Facet;
use facet_validate as validate;

fn validate_positive(n: &i64) -> Result<(), String> {
    if *n <= 0 {
        Err(format!("must be positive, got {}", n))
    } else {
        Ok(())
    }
}

#[derive(Facet)]
struct Product {
    #[facet(validate::custom = validate_positive)]
    price: i64,
}

Built-in validators

ValidatorSyntaxApplies to
minvalidate::min = 0numbers
maxvalidate::max = 100numbers
min_lengthvalidate::min_length = 1String, Vec, slices
max_lengthvalidate::max_length = 100String, Vec, slices
emailvalidate::emailString
urlvalidate::urlString
regexvalidate::regex = r"..."String
containsvalidate::contains = "foo"String
customvalidate::custom = fn_nameany

Auto-deref is supported: a fn(&str) validator works for String fields.

Integration

Enable the validate feature on facet-json (or another format crate):

toml
[dependencies]
facet-json     = { version = "0.41", features = ["validate"] }
facet-validate = "0.41"

Sponsors

Thanks to all individual sponsors:

GitHub Sponsors Patreon

...along with corporate sponsors:

AWS Zed Depot

...without whom this work could not exist.

Special thanks

The facet logo was drawn by Misiasart.

License

Licensed under either of:

at your option.