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    /// The form without the fields `names`, as if it had not sent them. The panel removes the
45    /// fields a [condition](crate::FieldConditions) hides before it checks and saves a form.
46    pub fn without<'n>(&self, names: impl IntoIterator<Item = &'n str>) -> FormInput {
47        let mut values = self.0.clone();
48        for name in names {
49            values.remove(name);
50        }
51        FormInput(values)
52    }
53
54    /// Sets the value of `name`.
55    pub(crate) fn insert(&mut self, name: String, value: String) {
56        self.0.insert(name, value);
57    }
58}
59
60/// Error messages for a form, keyed by field name. The panel shows each
61/// message next to its field when it re-renders the form.
62///
63/// The keys are owned `String`s, as the keys of Laravel's `MessageBag` are, so a
64/// runtime resource (whose field names are data) can report errors without leaking
65/// its names. A hand-written resource writes a literal key with `.to_string()`:
66///
67/// ```
68/// use ignite_core::FieldErrors;
69///
70/// let mut errors = FieldErrors::new();
71/// errors.insert("price".to_string(), "Price must be a whole number.".to_string());
72/// assert_eq!(errors.get("price").map(String::as_str), Some("Price must be a whole number."));
73/// ```
74///
75/// Since 0.3.0. Before, the keys were `&'static str`.
76pub type FieldErrors = HashMap<String, String>;
77
78/// A save the data layer refuses with a message on one or more fields, as Laravel's
79/// `ValidationException::withMessages(['field' => 'message'])`. A runtime resource's
80/// [`RuntimeData::try_create_for`](crate::RuntimeData::try_create_for) and
81/// [`try_update_for`](crate::RuntimeData::try_update_for) return it; the panel answers 422 with
82/// the form again, each message under its field and the typed values kept, as for the
83/// resource's own validation. Each key must be the name of a field the form shows: a message
84/// for another key has no slot to show in.
85#[derive(Debug, Clone, Default, PartialEq, Eq)]
86pub struct ValidationError {
87    errors: FieldErrors,
88}
89
90impl ValidationError {
91    /// The refusal with `messages`, as `(field, message)` pairs. A field named twice keeps its
92    /// last message.
93    pub fn with_messages<F, M>(messages: impl IntoIterator<Item = (F, M)>) -> Self
94    where
95        F: Into<String>,
96        M: Into<String>,
97    {
98        ValidationError {
99            errors: messages
100                .into_iter()
101                .map(|(field, message)| (field.into(), message.into()))
102                .collect(),
103        }
104    }
105
106    /// The messages, by field name.
107    pub fn errors(&self) -> &FieldErrors {
108        &self.errors
109    }
110
111    /// The messages, by field name, owned.
112    pub fn into_errors(self) -> FieldErrors {
113        self.errors
114    }
115}
116
117impl std::fmt::Display for ValidationError {
118    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
119        let mut fields: Vec<&str> = self.errors.keys().map(String::as_str).collect();
120        fields.sort_unstable();
121        write!(f, "the save was refused on: {}", fields.join(", "))
122    }
123}
124
125impl std::error::Error for ValidationError {}
126
127#[cfg(test)]
128mod tests {
129    use super::*;
130
131    fn form(pairs: &[(&str, &str)]) -> FormInput {
132        FormInput::new(
133            pairs
134                .iter()
135                .map(|(k, v)| (k.to_string(), v.to_string()))
136                .collect(),
137        )
138    }
139
140    #[test]
141    fn blank_and_missing_fields_are_none() {
142        let input = form(&[("name", "Ada"), ("email", "   ")]);
143
144        assert_eq!(input.get("name"), Some("Ada"));
145        assert_eq!(input.get("email"), None);
146        assert_eq!(input.get("missing"), None);
147    }
148
149    #[test]
150    fn checkbox_is_true_only_for_ticked_values() {
151        let input = form(&[
152            ("a", "on"),
153            ("b", "1"),
154            ("c", "TRUE"),
155            ("d", "0"),
156            ("e", ""),
157        ]);
158
159        assert!(input.checkbox("a"));
160        assert!(input.checkbox("b"));
161        assert!(input.checkbox("c"));
162        assert!(!input.checkbox("d"));
163        assert!(!input.checkbox("e"));
164        assert!(!input.checkbox("missing"));
165    }
166
167    #[test]
168    fn has_tells_a_blank_field_from_a_missing_one() {
169        let input = form(&[("name", "Ada"), ("note", "")]);
170
171        assert!(input.has("name"));
172        assert!(input.has("note"), "sent blank");
173        assert_eq!(input.get("note"), None);
174        assert!(!input.has("missing"));
175    }
176}