diff options
Diffstat (limited to 'src/validation/utils.rs')
-rw-r--r-- | src/validation/utils.rs | 54 |
1 files changed, 54 insertions, 0 deletions
diff --git a/src/validation/utils.rs b/src/validation/utils.rs new file mode 100644 index 0000000..4bff40a --- /dev/null +++ b/src/validation/utils.rs @@ -0,0 +1,54 @@ +use chrono::NaiveDate; +use std::collections::HashMap; +use std::str::FromStr; + +use crate::model::frequency::Frequency; + +pub fn non_empty( + form: &HashMap<String, String>, + field: &str, +) -> Option<String> { + let s = form.get(field)?.trim(); + if s.is_empty() { + None + } else { + Some(s.to_string()) + } +} + +pub fn parse<T: FromStr>( + form: &HashMap<String, String>, + field: &str, +) -> Option<T> { + let s = form.get(field)?; + s.parse::<T>().ok() +} + +pub fn date(form: &HashMap<String, String>, field: &str) -> Option<NaiveDate> { + let s = form.get(field)?; + NaiveDate::parse_from_str(s, "%Y-%m-%d").ok() +} + +pub fn frequency( + form: &HashMap<String, String>, + field: &str, +) -> Option<Frequency> { + let s = form.get(field)?; + Frequency::from_str(s).ok() +} + +pub fn color(form: &HashMap<String, String>, field: &str) -> Option<String> { + let s = form.get(field)?; + if s.len() == 7 + && &s[0..1] == "#" + && s[1..] + .to_string() + .into_bytes() + .into_iter() + .all(|c| c.is_ascii_hexdigit()) + { + Some(s.to_string()) + } else { + None + } +} |