aboutsummaryrefslogtreecommitdiff
path: root/src/validation/utils.rs
blob: 4bff40a8b305686a46170b2aee755dffd642ec22 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
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
    }
}