Crates.io | serde-validate |
lib.rs | serde-validate |
version | 0.2.0 |
source | src |
created_at | 2024-07-21 15:02:23.289362 |
updated_at | 2024-07-29 21:44:00.983242 |
description | A library for validating deserialized structs and enums |
homepage | |
repository | https://github.com/lucasmdjl/serde-validate |
max_upload_size | |
id | 1310393 |
size | 52,672 |
The serde-validate
crate provides utilities for validating deserialized structs and enums in Rust.
The core of the crate is the Validate
trait, which defines a method for validating instances of types and returning a custom error type if validation fails.
The crate also includes a procedural macro, validate_deser
, that generates deserialization code that validates the deserialized data.
Add this to your Cargo.toml
:
[dependencies]
serde-validate = "0.1"
To use the macro the macro
feature needs to be enabled (enabled by default):
[dependencies]
serde-validate = { version = "0.1", default-features = false, features = ["macro"] }
Implement the Validate
trait for your struct or enum to define custom validation logic.
use serde_validate::Validate;
use serde::Deserialize;
#[derive(Deserialize)]
struct MyStruct {
value: i32,
}
impl Validate for MyStruct {
type Error = String;
fn validate(&self) -> Result<(), Self::Error> {
if self.value < 0 {
Err("Value must be non-negative".into())
} else {
Ok(())
}
}
}
let my_struct = MyStruct { value: 10 };
assert!(my_struct.validate().is_ok());
Use the validate_deser
macro to automatically generate deserialization code that validates the deserialized data.
use serde-validate::{Validate, serde-validate};
#[validate_deser]
struct MyStruct {
value: i32,
}
impl Validate for MyStruct {
type Error = String;
fn validate(&self) -> Result<(), Self::Error> {
if self.value < 0 {
Err("Value must be non-negative".into())
} else {
Ok(())
}
}
}
// Assuming you have a JSON input as below:
let json_input = r#"{ "value": 10 }"#;
// Deserialize and validate the JSON input
let my_struct: Result<MyStruct, _> = serde_json::from_str(json_input);
assert!(my_struct.validate().is_ok());
// Assuming you have a JSON input as below:
let bad_json_input = r#"{ "value": -10 }"#;
// Deserialize and validate the JSON input
let my_struct: Result<MyStruct, _> = serde_json::from_str(bad_json_input);
assert!(my_struct.is_err());
This project is licensed under the GPL-3.0 License - see the LICENSE file for details.