| 586 | } |
| 587 | |
| 588 | fn validate_record( |
| 589 | record: csv::StringRecord, |
| 590 | line: u32, |
| 591 | cols: &[DataCol], |
| 592 | ) -> Result<(), Box<dyn Error>> { |
| 593 | for (idx, col) in cols.iter().enumerate() { |
| 594 | let field = &record[idx]; |
| 595 | |
| 596 | // Disallow beginning and trailng whitespace in entries |
| 597 | let trimmed_field = str::trim(field); |
| 598 | if field != trimmed_field { |
| 599 | return Err(format!( |
| 600 | "Remove beginning or trailing whitespace from entry in column \"{}\" on line {}\n", |
| 601 | col.name, line |
| 602 | ))?; |
| 603 | } |
| 604 | |
| 605 | if col.required { |
| 606 | let disallowed = ""; |
| 607 | match col.col_type { |
| 608 | ColType::Enum(enum_values) => { |
| 609 | if !enum_values.contains(&field) { |
| 610 | return Err(format!( |
| 611 | "Invalid entry: \"{}\" specified in required column \"{}\" on line {}.\n", |
| 612 | field, col.name, line |
| 613 | ))?; |
| 614 | } |
| 615 | } |
| 616 | ColType::NaiveDate => { |
| 617 | if trimmed_field == disallowed { |
| 618 | return Err(format!("Invalid entry: \"{}\" specified in required column \"{}\". Line {} does not abide.\n", field, col.name, line))?; |
| 619 | } else if NaiveDate::parse_from_str(field, "%Y-%m-%d").is_err() { |
| 620 | return Err(format!("Invalid date format entry: \"{}\" specified in column \"{}\" on line {}.\n Please use YYYY-MM-DD format.\n", field, col.name, line))?; |
| 621 | } |
| 622 | } |
| 623 | ColType::Other => { |
| 624 | if trimmed_field == disallowed { |
| 625 | return Err(format!("Invalid entry: \"{}\" specified in required column \"{}\". Line {} does not abide.\n", field, col.name, line))?; |
| 626 | } |
| 627 | } |
| 628 | } |
| 629 | } else { |
| 630 | match col.col_type { |
| 631 | ColType::Enum(enum_values) => { |
| 632 | if !enum_values.contains(&field) && &field != &"" { |
| 633 | return Err(format!( |
| 634 | "Invalid entry: \"{}\" specified in column \"{}\" on line {}.\n", |
| 635 | field, col.name, line |
| 636 | ))?; |
| 637 | } |
| 638 | } |
| 639 | ColType::NaiveDate => { |
| 640 | if field == ""{ |
| 641 | } |
| 642 | else if NaiveDate::parse_from_str(field, "%Y-%m-%d").is_err() { |
| 643 | return Err(format!("Invalid date format entry: \"{}\" specified in column \"{}\" on line {}.\n Please use YYYY-MM-DD format.\n", field, col.name, line))?; |
| 644 | } |
| 645 | } |