Skip to main content

lumen_dioxus/inputs/
input_form_errors.rs

1//! `FormErrors` and `FormFieldError`: form validation results, normalized like
2//! `normalizeLumenFormErrors` in lumen-core.
3
4/// One field's validation message.
5#[derive(Clone, Debug, Default, PartialEq, Eq)]
6pub struct FormFieldError {
7    /// The field name, such as `email`.
8    pub name: String,
9    /// The message shown to the user.
10    pub message: String,
11    /// Id of the visible control. [`ErrorSummary`](crate::ErrorSummary) links the message to it.
12    pub control_id: Option<String>,
13    /// An application error code, such as `required`.
14    pub code: Option<String>,
15}
16
17impl FormFieldError {
18    /// A message for the field `name`.
19    pub fn new(name: impl Into<String>, message: impl Into<String>) -> Self {
20        Self {
21            name: name.into(),
22            message: message.into(),
23            control_id: None,
24            code: None,
25        }
26    }
27
28    /// Returns the error linked to the control with this id.
29    #[must_use]
30    pub fn control_id(mut self, control_id: impl Into<String>) -> Self {
31        self.control_id = Some(control_id.into());
32        self
33    }
34
35    /// Returns the error with an application error code.
36    #[must_use]
37    pub fn code(mut self, code: impl Into<String>) -> Self {
38        self.code = Some(code.into());
39        self
40    }
41
42    /// The trimmed error, or `None` when the name or the message is blank. Empty control ids and
43    /// codes are dropped.
44    fn normalized(&self) -> Option<Self> {
45        let name = self.name.trim();
46        let message = self.message.trim();
47
48        if name.is_empty() || message.is_empty() {
49            return None;
50        }
51
52        Some(Self {
53            name: name.to_string(),
54            message: message.to_string(),
55            control_id: self.control_id.clone().filter(|id| !id.is_empty()),
56            code: self.code.clone().filter(|code| !code.is_empty()),
57        })
58    }
59}
60
61/// Validation errors for a whole form: form-level messages and field messages, like lumen-core's
62/// `LumenFormErrors`.
63///
64/// Build it from field errors, from `(name, message)` pairs (the names `form` and `root` hold
65/// form-level messages, and pairs never link to a control, like lumen-core's record input), or
66/// field by field:
67///
68/// ```
69/// use lumen_dioxus::{FormErrors, FormFieldError};
70///
71/// let from_pairs = FormErrors::from(vec![("form", "Try again."), ("email", "Enter an email.")]);
72/// let from_fields = FormErrors::from(vec![
73///     FormFieldError::new("email", "Enter an email.").control_id("email"),
74/// ]);
75///
76/// assert_eq!(from_pairs.form, vec!["Try again.".to_string()]);
77/// assert_eq!(from_fields.fields[0].control_id.as_deref(), Some("email"));
78/// ```
79#[derive(Clone, Debug, Default, PartialEq, Eq)]
80pub struct FormErrors {
81    /// Field messages, in order.
82    pub fields: Vec<FormFieldError>,
83    /// Form-level messages, in order.
84    pub form: Vec<String>,
85}
86
87impl FormErrors {
88    /// Whether there is no message at all.
89    pub fn is_empty(&self) -> bool {
90        self.fields.is_empty() && self.form.is_empty()
91    }
92
93    /// The errors with trimmed text, without blank messages, and without field errors that have
94    /// no name, like `normalizeLumenFormErrors`.
95    #[must_use]
96    pub fn normalized(&self) -> Self {
97        Self {
98            fields: self
99                .fields
100                .iter()
101                .filter_map(FormFieldError::normalized)
102                .collect(),
103            form: compact_messages(&self.form),
104        }
105    }
106
107    /// The normalized messages of one field.
108    pub fn field(&self, name: &str) -> Vec<FormFieldError> {
109        self.normalized()
110            .fields
111            .into_iter()
112            .filter(|error| error.name == name)
113            .collect()
114    }
115}
116
117fn compact_messages(messages: &[String]) -> Vec<String> {
118    messages
119        .iter()
120        .map(|message| message.trim())
121        .filter(|message| !message.is_empty())
122        .map(str::to_string)
123        .collect()
124}
125
126impl From<Vec<FormFieldError>> for FormErrors {
127    fn from(fields: Vec<FormFieldError>) -> Self {
128        Self {
129            fields,
130            form: Vec::new(),
131        }
132    }
133}
134
135impl<N: Into<String>, M: Into<String>> From<Vec<(N, M)>> for FormErrors {
136    fn from(pairs: Vec<(N, M)>) -> Self {
137        let mut errors = Self::default();
138
139        for (name, message) in pairs {
140            let name = name.into();
141            let message = message.into();
142
143            if name == "form" || name == "root" {
144                errors.form.push(message);
145            } else {
146                errors.fields.push(FormFieldError::new(name, message));
147            }
148        }
149
150        errors
151    }
152}
153
154#[cfg(test)]
155mod tests {
156    use super::{FormErrors, FormFieldError};
157
158    #[test]
159    fn pairs_split_form_and_field_messages() {
160        let errors = FormErrors::from(vec![
161            ("form", " Try again. "),
162            ("email", "Enter an email."),
163            ("root", ""),
164            ("name", "  "),
165        ])
166        .normalized();
167
168        assert_eq!(errors.form, vec!["Try again.".to_string()]);
169        assert_eq!(
170            errors.fields,
171            vec![FormFieldError::new("email", "Enter an email.")]
172        );
173    }
174
175    #[test]
176    fn field_errors_are_trimmed_and_blank_ones_dropped() {
177        let errors = FormErrors {
178            fields: vec![
179                FormFieldError::new(" email ", " Enter an email. ")
180                    .control_id("email")
181                    .code("required"),
182                FormFieldError::new("", "No name"),
183                FormFieldError::new("name", ""),
184                FormFieldError::new("age", "Too young").control_id(""),
185            ],
186            form: vec![" ".to_string(), "Server error".to_string()],
187        }
188        .normalized();
189
190        assert_eq!(errors.form, vec!["Server error".to_string()]);
191        assert_eq!(
192            errors.fields,
193            vec![
194                FormFieldError::new("email", "Enter an email.")
195                    .control_id("email")
196                    .code("required"),
197                FormFieldError::new("age", "Too young"),
198            ]
199        );
200        assert_eq!(errors.field("age").len(), 1);
201        assert_eq!(errors.field("missing"), Vec::<FormFieldError>::new());
202        assert!(FormErrors::default().is_empty());
203        assert!(!errors.is_empty());
204    }
205}