Skip to main content

impl_rules

Macro impl_rules 

Source
macro_rules! impl_rules {
    (
        $name:ident {
            $( $field:ident $(as $rename:literal)? => $schema:expr ),* $(,)?
        }
    ) => { ... };
}
Expand description

Attach validation rules to an existing struct.

Unlike schema! which creates the struct, this macro takes a struct you already have and generates validate() and is_valid() instance methods.

The struct itself does not need serde::Serialize (or Debug): each listed field is serialized individually, so only the field types must implement Serialize (standard types like String, f64, Vec<T> do). A field that fails to serialize is reported as serialize_error.

ยงExample

use vld::prelude::*;

// No Serialize or Debug required on the struct itself
struct Product {
    name: String,
    price: f64,
    tags: Vec<String>,
}

vld::impl_rules!(Product {
    name => vld::string().min(2).max(100),
    price => vld::number().positive(),
    tags => vld::array(vld::string().min(1)).max_len(10),
});

let p = Product {
    name: "Widget".into(),
    price: 9.99,
    tags: vec!["sale".into()],
};
assert!(p.is_valid());

let bad = Product {
    name: "X".into(),
    price: -1.0,
    tags: vec![],
};
assert!(!bad.is_valid());
let err = bad.validate().unwrap_err();
assert!(err.issues.len() >= 2);

Use field as "wireName" => schema to report errors under the JSON name (e.g. when the struct uses #[serde(rename = ...)]).