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.
Code
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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.Credit Card Brand DetectorIdentify the card network from a number's prefix and length, validate the Luhn checksum, and show a masked form and the issuer identification number.
FAQ
- What does Accumulate Every Validation Failure print when run?
- The script runs standalone; its 1 labeled outputs include `form accepted`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.