form_validation/concat_results.rs
1use crate::ValidationErrors;
2
3/// Join validation results, concatinating any errors they may
4/// contain. If any of the results are an `Err` it will return an
5/// `Err` containing all the errors from all the results.
6///
7/// ## Example
8/// ```
9/// use form_validation::{concat_results, ValidationError, ValidationErrors};
10/// let results = vec![
11/// Ok(()),
12/// Err(ValidationErrors::new(vec![ValidationError::new("field1", "TEST_ERROR1")])),
13/// Err(ValidationErrors::new(vec![ValidationError::new("field1", "TEST_ERROR2")])),
14/// Err(ValidationErrors::new(vec![ValidationError::new("field2", "TEST_ERROR1")])),
15/// ];
16///
17/// let result = concat_results(results);
18///
19/// let errors = result.unwrap_err();
20///
21/// assert_eq!(3, errors.len());
22///
23/// let field1_errors = errors.get(&"field1").unwrap();
24/// assert_eq!(2, field1_errors.len());
25///
26/// let field2_errors = errors.get(&"field2").unwrap();
27/// assert_eq!(1, field2_errors.len());
28/// ```
29pub fn concat_results<Key>(
30 results: Vec<Result<(), ValidationErrors<Key>>>,
31) -> Result<(), ValidationErrors<Key>>
32where
33 Key: PartialEq + Clone,
34{
35 let mut all_errors: ValidationErrors<Key> = ValidationErrors::default();
36
37 for result in results {
38 if let Err(errors) = result {
39 all_errors.extend(errors);
40 }
41 }
42
43 if !all_errors.is_empty() {
44 Err(all_errors)
45 } else {
46 Ok(())
47 }
48}