Rust field-level input validation with error list
Rust
#[derive(Debug)]
struct Signup {
email: String,
age: u8,
password: String,
}
fn validate(s: &Signup) -> Result<(), Vec<(&'static str, String)>> {
let mut errors = Vec::new();
if !s.email.contains('@') {
errors.push(("email", "must contain @".into()));
}
if s.age < 13 {
errors.push(("age", "must be 13 or older".into()));
}
if s.password.len() < 8 {
errors.push(("password", "must be at least 8 characters".into()));
}
if errors.is_empty() { Ok(()) } else { Err(errors) }
}