Skip to main content

ValidationError

Struct ValidationError 

Source
pub struct ValidationError { /* private fields */ }
Expand description

One or more validation failures collected during validation.

ValidationError is designed for multi-field struct validation where all fields should be checked and all violations reported together. For single-value validation, a simpler error type may be more appropriate.

Requires the alloc feature (enabled by default via std), since it is backed by Vec<Violation>.

Implementations§

Source§

impl ValidationError

Source

pub fn new(message: &'static str) -> Self

Creates a ValidationError with a single unnamed violation.

Source

pub fn field(field: &'static str, message: &'static str) -> Self

Creates a ValidationError with a single named field violation.

Source

pub fn empty() -> Self

Creates an empty ValidationError. Useful for building up violations.

Always check is_empty before returning this as Err. Returning an empty ValidationError is valid Rust but conveys no information to the caller.

Examples found in repository?
examples/basic.rs (line 20)
19    fn validate(&self) -> Result<(), Self::Error> {
20        let mut errors = ValidationError::empty();
21
22        if self.username.len() < 3 {
23            errors.push(Violation::with_field(
24                "username",
25                "must be at least 3 characters",
26            ));
27        }
28        if self.age < 18 {
29            errors.push(Violation::with_field("age", "must be 18 or older"));
30        }
31        if !self.email.contains('@') {
32            errors.push(Violation::with_field("email", "must contain '@'"));
33        }
34
35        if errors.is_empty() {
36            Ok(())
37        } else {
38            Err(errors)
39        }
40    }
Source

pub fn with(self, violation: Violation) -> Self

Adds a violation and returns self for chaining.

Source

pub fn push(&mut self, violation: Violation)

Adds a violation in place.

Examples found in repository?
examples/basic.rs (lines 23-26)
19    fn validate(&self) -> Result<(), Self::Error> {
20        let mut errors = ValidationError::empty();
21
22        if self.username.len() < 3 {
23            errors.push(Violation::with_field(
24                "username",
25                "must be at least 3 characters",
26            ));
27        }
28        if self.age < 18 {
29            errors.push(Violation::with_field("age", "must be 18 or older"));
30        }
31        if !self.email.contains('@') {
32            errors.push(Violation::with_field("email", "must contain '@'"));
33        }
34
35        if errors.is_empty() {
36            Ok(())
37        } else {
38            Err(errors)
39        }
40    }
Source

pub fn merge(self, other: Self) -> Self

Merges another ValidationError into this one.

Source

pub fn require(self, condition: bool, violation: Violation) -> Self

Records violation only when condition is false, and returns self for chaining. A true condition means the rule held, so nothing is added.

Pair this with finish to express multi-field validation without the easy-to-forget final emptiness check:

use reliakit_validate::{ValidationError, Violation};

let result = ValidationError::empty()
    .require(!"".is_empty(), Violation::with_field("name", "must not be empty"))
    .require(15 >= 18, Violation::with_field("age", "must be at least 18"))
    .finish();

assert_eq!(result.unwrap_err().len(), 2);
Source

pub fn require_field( self, condition: bool, field: &'static str, message: &'static str, ) -> Self

Like require, building the Violation from a field name and message.

Source

pub fn finish(self) -> ValidateResult

Converts the accumulated violations into a result: Ok(()) when there are none, otherwise Err(self).

This removes the footgun of returning an empty ValidationError as an error (see empty).

Source

pub fn violations(&self) -> &[Violation]

Returns all violations.

Examples found in repository?
examples/basic.rs (line 54)
43fn main() {
44    let bad = Signup {
45        username: "jo".into(),
46        age: 15,
47        email: "nope".into(),
48    };
49
50    match bad.validate() {
51        Ok(()) => println!("valid"),
52        Err(errors) => {
53            println!("{} problem(s):", errors.len());
54            for v in errors.violations() {
55                println!("  - {}: {}", v.field.unwrap_or("(form)"), v.message);
56            }
57        }
58    }
59
60    let good = Signup {
61        username: "jordan".into(),
62        age: 30,
63        email: "jordan@example.com".into(),
64    };
65    println!("good signup valid: {}", good.validate().is_ok());
66}
Source

pub fn is_empty(&self) -> bool

Returns true if there are no violations.

Examples found in repository?
examples/basic.rs (line 35)
19    fn validate(&self) -> Result<(), Self::Error> {
20        let mut errors = ValidationError::empty();
21
22        if self.username.len() < 3 {
23            errors.push(Violation::with_field(
24                "username",
25                "must be at least 3 characters",
26            ));
27        }
28        if self.age < 18 {
29            errors.push(Violation::with_field("age", "must be 18 or older"));
30        }
31        if !self.email.contains('@') {
32            errors.push(Violation::with_field("email", "must contain '@'"));
33        }
34
35        if errors.is_empty() {
36            Ok(())
37        } else {
38            Err(errors)
39        }
40    }
Source

pub fn len(&self) -> usize

Returns the number of violations.

Examples found in repository?
examples/basic.rs (line 53)
43fn main() {
44    let bad = Signup {
45        username: "jo".into(),
46        age: 15,
47        email: "nope".into(),
48    };
49
50    match bad.validate() {
51        Ok(()) => println!("valid"),
52        Err(errors) => {
53            println!("{} problem(s):", errors.len());
54            for v in errors.violations() {
55                println!("  - {}: {}", v.field.unwrap_or("(form)"), v.message);
56            }
57        }
58    }
59
60    let good = Signup {
61        username: "jordan".into(),
62        age: 30,
63        email: "jordan@example.com".into(),
64    };
65    println!("good signup valid: {}", good.validate().is_ok());
66}

Trait Implementations§

Source§

impl Clone for ValidationError

Source§

fn clone(&self) -> ValidationError

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for ValidationError

Source§

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

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

impl Display for ValidationError

Available on crate feature alloc only.
Source§

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

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

impl Eq for ValidationError

Source§

impl Error for ValidationError

Available on crate feature std only.
1.30.0 · Source§

fn source(&self) -> Option<&(dyn Error + 'static)>

Returns the lower-level source of this error, if any. Read more
1.0.0 · Source§

fn description(&self) -> &str

👎Deprecated since 1.42.0:

use the Display impl or to_string()

1.0.0 · Source§

fn cause(&self) -> Option<&dyn Error>

👎Deprecated since 1.33.0:

replaced by Error::source, which can support downcasting

Source§

fn provide<'a>(&'a self, request: &mut Request<'a>)

🔬This is a nightly-only experimental API. (error_generic_member_access)
Provides type-based access to context intended for error reports. Read more
Source§

impl Extend<Violation> for ValidationError

Available on crate feature alloc only.
Source§

fn extend<I: IntoIterator<Item = Violation>>(&mut self, iter: I)

Extends a collection with the contents of an iterator. Read more
Source§

fn extend_one(&mut self, item: A)

🔬This is a nightly-only experimental API. (extend_one)
Extends a collection with exactly one element.
Source§

fn extend_reserve(&mut self, additional: usize)

🔬This is a nightly-only experimental API. (extend_one)
Reserves capacity in a collection for the given number of additional elements. Read more
Source§

impl From<&'static str> for ValidationError

Available on crate feature alloc only.
Source§

fn from(message: &'static str) -> Self

Converts to this type from the input type.
Source§

impl From<Violation> for ValidationError

Available on crate feature alloc only.
Source§

fn from(v: Violation) -> Self

Converts to this type from the input type.
Source§

impl FromIterator<Violation> for ValidationError

Available on crate feature alloc only.
Source§

fn from_iter<I: IntoIterator<Item = Violation>>(iter: I) -> Self

Creates a value from an iterator. Read more
Source§

impl PartialEq for ValidationError

Source§

fn eq(&self, other: &ValidationError) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl StructuralPartialEq for ValidationError

Auto Trait Implementations§

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
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> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

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

Source§

type Error = Infallible

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

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

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.