Skip to main content

ValidationError

Struct ValidationError 

Source
pub struct ValidationError {
    pub field: String,
    pub message: String,
}
Expand description

Error type for validation failures

Fields§

§field: String§message: String

Implementations§

Source§

impl ValidationError

Source

pub fn new(field: impl Into<String>, message: impl Into<String>) -> Self

Examples found in repository?
examples/error_handling.rs (line 23)
18    fn validate(&self) -> Result<(), Vec<ValidationError>> {
19        let mut errors = Vec::new();
20
21        // Validate email
22        if !is_valid_email(&self.email) {
23            errors.push(ValidationError::new("email", "Invalid email format"));
24        }
25
26        // Validate phone
27        if !is_valid_phone(&self.phone) {
28            errors.push(ValidationError::new("phone", "Invalid phone number"));
29        }
30
31        // Validate website
32        if !is_valid_https_url(&self.website) {
33            errors.push(ValidationError::new("website", "Must be a valid HTTPS URL"));
34        }
35
36        // Validate credit card
37        if !credit_card::is_valid_credit_card(&self.credit_card) {
38            errors.push(ValidationError::new("credit_card", "Invalid credit card number"));
39        }
40
41        if errors.is_empty() {
42            Ok(())
43        } else {
44            Err(errors)
45        }
46    }
47}
48
49/// Validates a password with multiple rules
50fn validate_password(password: &str) -> Result<(), Vec<String>> {
51    let mut errors = Vec::new();
52
53    if !string::has_min_length(password, 8) {
54        errors.push("Password must be at least 8 characters long".to_string());
55    }
56
57    if !string::has_max_length(password, 128) {
58        errors.push("Password must not exceed 128 characters".to_string());
59    }
60
61    if !password.chars().any(|c| c.is_uppercase()) {
62        errors.push("Password must contain at least one uppercase letter".to_string());
63    }
64
65    if !password.chars().any(|c| c.is_lowercase()) {
66        errors.push("Password must contain at least one lowercase letter".to_string());
67    }
68
69    if !password.chars().any(|c| c.is_ascii_digit()) {
70        errors.push("Password must contain at least one digit".to_string());
71    }
72
73    if !password.chars().any(|c| !c.is_alphanumeric()) {
74        errors.push("Password must contain at least one special character".to_string());
75    }
76
77    if errors.is_empty() {
78        Ok(())
79    } else {
80        Err(errors)
81    }
82}
83
84/// Validates age with range checking
85fn validate_age(age: i32) -> ValidationResult {
86    if !numeric::is_in_range(age, 18, 120) {
87        return Err(ValidationError::new("age", "Age must be between 18 and 120"));
88    }
89    Ok(())
90}

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

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

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 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.