Validate

Trait Validate 

Source
pub trait Validate {
    // Required method
    fn validate(&self) -> Result<(), ValidationErrors>;

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

Trait for synchronous validation of a struct.

Implement this trait to enable validation on your types.

§Example

use rustapi_validate::v2::prelude::*;

struct User {
    email: String,
    age: u8,
}

impl Validate for User {
    fn validate(&self) -> Result<(), ValidationErrors> {
        let mut errors = ValidationErrors::new();
         
        if let Err(e) = EmailRule::default().validate(&self.email) {
            errors.add("email", e);
        }
         
        if let Err(e) = RangeRule::new(18, 120).validate(&self.age) {
            errors.add("age", e);
        }
         
        errors.into_result()
    }
}

Required Methods§

Source

fn validate(&self) -> Result<(), ValidationErrors>

Validate the struct synchronously.

Returns Ok(()) if validation passes, or Err(ValidationErrors) with all field errors.

Provided Methods§

Source

fn validated(self) -> Result<Self, ValidationErrors>
where Self: Sized,

Validate and return the struct if valid.

Implementors§