Crate serde_validate

Source
Expand description

§serde-validate

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 serde-validate-macro, serde-validate, that generates deserialization code that validates the deserialized data.

§Example

use serde_validate::{Validate, validate_deser};

#[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 good_json_input = r#"{ "value": 10 }"#;

// Deserialize and validate the JSON input
let my_struct: Result<MyStruct, _> = serde_json::from_str(good_json_input);
assert!(my_struct.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());

Traits§

Validate
The Validate trait defines the contract for validating deserialized structs.

Attribute Macros§

validate_deser
Attribute serde-validate-macro to derive deserialization with validation for a struct or enum.