Skip to main content

validate_basic/
basic.rs

1//! Collect every validation error at once instead of failing on the first.
2//!
3//! ```sh
4//! cargo run -p reliakit-validate --example basic
5//! ```
6
7use reliakit_validate::{Validate, ValidationError, Violation};
8
9/// A signup form validated as a whole, so the user sees every problem in one go.
10struct Signup {
11    username: String,
12    age: u32,
13    email: String,
14}
15
16impl Validate for Signup {
17    type Error = ValidationError;
18
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    }
41}
42
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}