macro_rules! impl_rules {
(
$name:ident {
$( $field:ident => $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 must implement serde::Serialize.
The struct does not need #[derive(Serialize)] or #[derive(Debug)] —
each field is serialized individually (standard types like String, f64,
Vec<T> already implement Serialize).
§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);