multi_validation/
multi_validation.rs1use std::error::Error;
6
7use scoped_error::Many;
8use scoped_error::impl_context_error;
9
10impl_context_error!(ValidationError);
11
12impl ValidationError {
13 fn new(msg: &'static str) -> Self {
14 Self {
15 message: msg.into(),
16 source: None,
17 location: None,
18 }
19 }
20}
21
22struct UserInput {
23 name: String,
24 email: String,
25 age: u32,
26}
27
28fn validate_user(input: &UserInput) -> Result<(), Many> {
29 let mut errors = Vec::new();
30
31 if input.name.is_empty() {
32 errors.push(ValidationError::new("name is required"));
33 }
34 if input.email.is_empty() {
35 errors.push(ValidationError::new("email is required"));
36 }
37 if input.age < 18 {
38 errors.push(ValidationError::new("must be 18 or older"));
39 }
40
41 if errors.is_empty() {
42 Ok(())
43 } else {
44 Err(Many::from_errors("user validation failed", errors))
45 }
46}
47
48fn main() -> Result<(), Box<dyn Error>> {
49 validate_user(&UserInput {
50 name: "John".to_string(),
51 email: "".to_string(),
52 age: 14,
53 })?;
54 Ok(())
55}