Skip to main content

ignite_core/
form.rs

1//! Submitted form values and the per-field error messages.
2
3use std::collections::HashMap;
4
5/// Submitted form values, by field name. Empty fields are `None`.
6#[derive(Debug, Clone, Default, PartialEq, Eq)]
7pub struct FormInput(HashMap<String, String>);
8
9impl FormInput {
10    /// Wraps the values of a submitted form, keyed by field name.
11    pub fn new(values: HashMap<String, String>) -> Self {
12        FormInput(values)
13    }
14
15    /// Returns the value of `name`, or `None` when the field is missing or
16    /// blank. The value is not trimmed.
17    pub fn get(&self, name: &str) -> Option<&str> {
18        self.0
19            .get(name)
20            .map(String::as_str)
21            .filter(|value| !value.trim().is_empty())
22    }
23
24    /// Returns true when the form sent the field `name` at all, even blank. A field that is
25    /// sent blank is one the user cleared; a field that is not sent is one the form does not
26    /// have, so an update keeps its stored value. An unticked HTML checkbox sends nothing, so
27    /// use [`checkbox`](Self::checkbox) for a checkbox, not this.
28    pub fn has(&self, name: &str) -> bool {
29        self.0.contains_key(name)
30    }
31
32    /// Returns true when the checkbox `name` was ticked. An HTML checkbox
33    /// sends `on` when ticked and nothing when not, so `on`, `1` and `true`
34    /// (in any case) count as ticked.
35    pub fn checkbox(&self, name: &str) -> bool {
36        self.get(name).is_some_and(|value| {
37            matches!(
38                value.trim().to_ascii_lowercase().as_str(),
39                "on" | "1" | "true"
40            )
41        })
42    }
43}
44
45/// Error messages for a form, keyed by field name. The panel shows each
46/// message next to its field when it re-renders the form.
47///
48/// The keys are owned `String`s, as the keys of Laravel's `MessageBag` are, so a
49/// runtime resource (whose field names are data) can report errors without leaking
50/// its names. A hand-written resource writes a literal key with `.to_string()`:
51///
52/// ```
53/// use ignite_core::FieldErrors;
54///
55/// let mut errors = FieldErrors::new();
56/// errors.insert("price".to_string(), "Price must be a whole number.".to_string());
57/// assert_eq!(errors.get("price").map(String::as_str), Some("Price must be a whole number."));
58/// ```
59///
60/// Since 0.3.0. Before, the keys were `&'static str`.
61pub type FieldErrors = HashMap<String, String>;
62
63#[cfg(test)]
64mod tests {
65    use super::*;
66
67    fn form(pairs: &[(&str, &str)]) -> FormInput {
68        FormInput::new(
69            pairs
70                .iter()
71                .map(|(k, v)| (k.to_string(), v.to_string()))
72                .collect(),
73        )
74    }
75
76    #[test]
77    fn blank_and_missing_fields_are_none() {
78        let input = form(&[("name", "Ada"), ("email", "   ")]);
79
80        assert_eq!(input.get("name"), Some("Ada"));
81        assert_eq!(input.get("email"), None);
82        assert_eq!(input.get("missing"), None);
83    }
84
85    #[test]
86    fn checkbox_is_true_only_for_ticked_values() {
87        let input = form(&[
88            ("a", "on"),
89            ("b", "1"),
90            ("c", "TRUE"),
91            ("d", "0"),
92            ("e", ""),
93        ]);
94
95        assert!(input.checkbox("a"));
96        assert!(input.checkbox("b"));
97        assert!(input.checkbox("c"));
98        assert!(!input.checkbox("d"));
99        assert!(!input.checkbox("e"));
100        assert!(!input.checkbox("missing"));
101    }
102
103    #[test]
104    fn has_tells_a_blank_field_from_a_missing_one() {
105        let input = form(&[("name", "Ada"), ("note", "")]);
106
107        assert!(input.has("name"));
108        assert!(input.has("note"), "sent blank");
109        assert_eq!(input.get("note"), None);
110        assert!(!input.has("missing"));
111    }
112}