Skip to main content

Validated

Struct Validated 

Source
pub struct Validated<T, V = ()> { /* private fields */ }
Expand description

A value that might be invalid, together with its errors.

Deserializing a Validated never fails: the errors of the value are kept in it instead of failing the deserialization of the value it’s in. That covers the errors of the value itself (for instance a string where a number is expected), of the values nested in it and the violation of the validator V (none by default). Within the value, all errors are collected (see State::set_collect_errors): the error holds all problems of the value, not just the first one. Only the errors of the data format and of layers (for instance Limits) still fail the deserialization, and the error that exceeds the limit of errors (see State::set_max_errors).

use deser::Deserialize;
use deser_validate::{Email, Validated};

#[derive(Deserialize)]
struct Signup {
    email: Validated<String, Email>,
    age: Validated<u8>,
}

let signup: Signup =
    deser_json::from_str(r#"{"email": "nope", "age": "x"}"#).unwrap();
assert!(!signup.email.is_valid());
assert_eq!(signup.email.unchecked_value().unwrap(), "nope");
assert_eq!(
    signup.email.error().unwrap().to_string(),
    "InvalidValue: invalid value: must be an email address at offset 10"
);
assert_eq!(signup.age.value(), None);

The errors have the context of the value attached, like errors that are returned (for instance the path with a PathLayer). If the format provides the source (see deser_location), their lines and columns are resolved. If a Validation runs, they are reported to it too.

While an untagged enum tries its variants, errors are not kept: a variant with an invalid Validated value does not match.

use deser::Deserialize;
use deser_validate::Validated;

#[derive(Deserialize)]
struct Address {
    street: String,
    zip: u32,
}

#[derive(Deserialize)]
struct Order {
    shipping: Validated<Address>,
}

let order: Order =
    deser_json::from_str(r#"{"shipping": {"zip": "x"}}"#).unwrap();
let err = order.shipping.error().unwrap();
let errors: Vec<_> = err.errors().map(|err| err.message()).collect();
assert_eq!(
    errors,
    ["unexpected string, expected u32", "missing field `street`"]
);

When serialized, the value is serialized (also if it’s invalid), a value that could not be deserialized is serialized as null.

Implementations§

Source§

impl<T, V: Validator<T>> Validated<T, V>

Source

pub fn new(value: T) -> Validated<T, V>

Validates a value.

Source§

impl<T, V> Validated<T, V>

Source

pub fn from_error(error: Error) -> Validated<T, V>

Creates an invalid value from an error.

Source

pub fn is_valid(&self) -> bool

Returns true if the value is valid.

Source

pub fn value(&self) -> Option<&T>

Returns the value if it’s valid.

Source

pub fn unchecked_value(&self) -> Option<&T>

Returns the value, also if the validator rejected it.

Returns None if the value could not be deserialized.

Source

pub fn error(&self) -> Option<&Error>

Returns the error if the value is invalid.

The error holds all errors of the value (see Error::errors).

Source

pub fn into_result(self) -> Result<T, Error>

Returns the value if it’s valid and the error otherwise.

Trait Implementations§

Source§

impl<T: Debug, V> Debug for Validated<T, V>

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<'de, T: Deserialize<'de>, V: Validator<T>> Deserialize<'de> for Validated<T, V>

Source§

fn initial_value() -> Option<Self>

Missing values are the missing values of T (validated).

Source§

fn deserialize_into<'out>( out: &'out mut Option<Self>, state: &mut State, ) -> SinkHandle<'out, 'de>

Creates a sink that deserializes the value into the given slot. Read more
Source§

fn expecting() -> Cow<'static, str>

Returns what the value expects, for error messages. Read more
Source§

fn describe_type(d: &mut dyn Describe)

Describes the Rust shape of the type. Read more
Source§

fn deserialize_atom( slot: &mut Slot<T, Self>, atom: Atom<'_>, state: &mut State, ) -> Result<(), Error>

Deserializes an atom into the slot. Read more
Source§

fn deserialize_borrowed_atom( slot: &mut Slot<T, Self>, atom: Atom<'de>, state: &mut State, ) -> Result<(), Error>

Deserializes an atom that borrows from the data being deserialized into the slot. Read more
Source§

fn deserialize_update<'out>( value: &'out mut T, state: &mut State, ) -> SinkHandle<'out, 'de>

Creates a sink that updates an existing value. Read more
Source§

impl<T: Serialize, V> Serialize for Validated<T, V>

Source§

fn serialize<'a>(this: &'a Self, state: &mut State) -> Result<Emit<'a>, Error>

Serializes the value.
Source§

fn finish(this: &Self, state: &mut State) -> Result<(), Error>

Invoked after the serialization finished. Read more
Source§

fn is_optional(this: &Self) -> bool

Checks if the value represents an optional value. Read more
Source§

fn container_shape(this: &Self) -> ContainerShape

Returns the shape of the value if it’s a map or sequence. Read more
Source§

fn describe(this: &Self, d: &mut dyn Describe)

Describes the Rust shape of the value. Read more

Auto Trait Implementations§

§

impl<T, V = ()> !RefUnwindSafe for Validated<T, V>

§

impl<T, V = ()> !UnwindSafe for Validated<T, V>

§

impl<T, V> Freeze for Validated<T, V>
where Option<T>: Freeze, PhantomData<fn() -> V>: Freeze,

§

impl<T, V> Send for Validated<T, V>
where Option<T>: Send, PhantomData<fn() -> V>: Send,

§

impl<T, V> Sync for Validated<T, V>
where Option<T>: Sync, PhantomData<fn() -> V>: Sync,

§

impl<T, V> Unpin for Validated<T, V>
where Option<T>: Unpin, PhantomData<fn() -> V>: Unpin,

§

impl<T, V> UnsafeUnpin for Validated<T, V>

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.