Accumulate Every Validation Failure

Running every validation rule and flattening the Option failures into one Vec reports all problems at once instead of stopping at the first.

RustForm Validation

Code

rustsnippet
46 lines
fn validate_name(name: &str) -> Option<String> {
    if name.is_empty() {
        Some(String::from("name is empty"))
    } else {
        None
    }
}

fn validate_age(age: u32) -> Option<String> {
    if age > 130 {
        Some(format!("age {age} exceeds 130"))
    } else {
        None
    }
}

fn validate_email(email: &str) -> Option<String> {
    if !email.contains('@') {
        Some(format!("email {email:?} missing @"))
    } else {
        None
    }
}

fn main() {
    let form = ("", 200u32, "not-an-email");

    // fail-slow: every rule runs, collecting all failures into a Vec instead of stopping at the first
    let problems: Vec<String> = [
        validate_name(form.0),
        validate_age(form.1),
        validate_email(form.2),
    ]
    .into_iter()
    .flatten()
    .collect();

    if problems.is_empty() {
        println!("form accepted");
    } else {
        println!("{} problems:", problems.len());
        for problem in &problems {
            println!("- {problem}");
        }
    }
}

Inside the snippet

The code’s whole job belongs to the functions validate_name, validate_age, validate_email and main.

Repetition is confined to for problem in &problems — the rest of the file is straight-line.

Using it

Entry signature: fn validate_name(name: &str) -> Option<String>

Running the file prints labeled results such as form accepted — each operation’s effect is visible in the output.

main sequences validate_name, validate_age and validate_email; executing the file runs that flow once.

Key statements

fn validate_email(email: &str) -> Option<String> {
    if !email.contains('@') {
        Some(format!("email {email:?} missing @"))
    } else {
        None
    }
}
fn validate_name(name: &str) -> Option<String> {
    if name.is_empty() {
        Some(String::from("name is empty"))
    } else {
        None
    }
}
fn validate_age(age: u32) -> Option<String> {
    if age > 130 {
        Some(format!("age {age} exceeds 130"))
    } else {
        None
    }
}

Interactive Tools for This Topic

FAQ

What does Accumulate Every Validation Failure print when run?
The script runs standalone; its 1 labeled outputs include `form accepted`.