use std::collections::HashMap;
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct FormInput(HashMap<String, String>);
impl FormInput {
pub fn new(values: HashMap<String, String>) -> Self {
FormInput(values)
}
pub fn get(&self, name: &str) -> Option<&str> {
self.0
.get(name)
.map(String::as_str)
.filter(|value| !value.trim().is_empty())
}
pub fn has(&self, name: &str) -> bool {
self.0.contains_key(name)
}
pub fn checkbox(&self, name: &str) -> bool {
self.get(name).is_some_and(|value| {
matches!(
value.trim().to_ascii_lowercase().as_str(),
"on" | "1" | "true"
)
})
}
}
pub type FieldErrors = HashMap<String, String>;
#[cfg(test)]
mod tests {
use super::*;
fn form(pairs: &[(&str, &str)]) -> FormInput {
FormInput::new(
pairs
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect(),
)
}
#[test]
fn blank_and_missing_fields_are_none() {
let input = form(&[("name", "Ada"), ("email", " ")]);
assert_eq!(input.get("name"), Some("Ada"));
assert_eq!(input.get("email"), None);
assert_eq!(input.get("missing"), None);
}
#[test]
fn checkbox_is_true_only_for_ticked_values() {
let input = form(&[
("a", "on"),
("b", "1"),
("c", "TRUE"),
("d", "0"),
("e", ""),
]);
assert!(input.checkbox("a"));
assert!(input.checkbox("b"));
assert!(input.checkbox("c"));
assert!(!input.checkbox("d"));
assert!(!input.checkbox("e"));
assert!(!input.checkbox("missing"));
}
#[test]
fn has_tells_a_blank_field_from_a_missing_one() {
let input = form(&[("name", "Ada"), ("note", "")]);
assert!(input.has("name"));
assert!(input.has("note"), "sent blank");
assert_eq!(input.get("note"), None);
assert!(!input.has("missing"));
}
}