Trait Validate

Source
pub trait Validate: Sized {
    type Error;

    // Required method
    fn validate(&self) -> Result<(), Self::Error>;

    // Provided method
    fn validated(self) -> Result<Self, Self::Error> { ... }
}
Expand description

The Validate trait defines the contract for validating deserialized structs.

Implementors of this trait are required to provide their own validation logic and an associated error type.

§Example

use serde_validate::Validate;

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());

Required Associated Types§

Source

type Error

The error type returned by the validate method.

Required Methods§

Source

fn validate(&self) -> Result<(), Self::Error>

Validates the instance, returning Ok(()) if serde-validate, or an Error otherwise.

Provided Methods§

Source

fn validated(self) -> Result<Self, Self::Error>

Consumes the instance, validating it and returning the instance itself if serde-validate.

This method provides a convenient way to validate and immediately use the instance.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety", so this trait is not object safe.

Implementors§