2 unstable releases
0.2.0 | Sep 13, 2024 |
---|---|
0.1.0 | Aug 25, 2024 |
#508 in #validation
Used in serdev
21KB
389 lines
SerdeV
SerdeV - Serde with Validation- Just a wrapper of Serde and 100% compatible
- Declarative validation in deserialization by
#[serde(validate = "...")]
Example
[dependencies]
serdev = "0.2"
serde_json = "1.0"
use serdev::{Serialize, Deserialize};
#[derive(Serialize, Deserialize, Debug)]
#[serde(validate = "Self::validate")]
struct Point {
x: i32,
y: i32,
}
impl Point {
fn validate(&self) -> Result<(), impl std::fmt::Display> {
if self.x * self.y > 100 {
return Err("x * y must not exceed 100")
}
Ok(())
}
}
fn main() {
let point = serde_json::from_str::<Point>(r#"
{ "x" : 1, "y" : 2 }
"#).unwrap();
// Prints point = Point { x: 1, y: 2 }
println!("point = {point:?}");
let error = serde_json::from_str::<Point>(r#"
{ "x" : 10, "y" : 20 }
"#).unwrap_err();
// Prints error = x * y must not exceed 100
println!("error = {error}");
}
Of course, you can use it in combination with some validation tools like validator! ( full example )
Attribute
-
#[serde(validate = "function")]
Automatically validate by the
function
in deserialization. Thefunction
must be callable asfn(&self) -> Result<(), impl Display>
.
Errors are converted to aString
internally and passed toserde::de::Error::custom
. -
#[serde(validate(by = "function", error = "Type"))]
Using given
Type
for validation error without internal conversion. Thefunction
must explicitly returnResult<(), Type>
.
This may be preferred when you need better performance even in error cases.
For no-std use, this is the only way supported.
Both "function"
and "Type"
accept path like "crate::util::validate"
.
Additionally, #[serdev(crate = "path::to::serdev")]
is supported for reexport from another crate.
License
Licensed under MIT LICENSE ( LICENSE or https://opensource.org/licenses/MIT ).
Dependencies
~215–650KB
~16K SLoC