lumen_dioxus/inputs/
input_form_errors.rs1#[derive(Clone, Debug, Default, PartialEq, Eq)]
6pub struct FormFieldError {
7 pub name: String,
9 pub message: String,
11 pub control_id: Option<String>,
13 pub code: Option<String>,
15}
16
17impl FormFieldError {
18 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 #[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 #[must_use]
37 pub fn code(mut self, code: impl Into<String>) -> Self {
38 self.code = Some(code.into());
39 self
40 }
41
42 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#[derive(Clone, Debug, Default, PartialEq, Eq)]
80pub struct FormErrors {
81 pub fields: Vec<FormFieldError>,
83 pub form: Vec<String>,
85}
86
87impl FormErrors {
88 pub fn is_empty(&self) -> bool {
90 self.fields.is_empty() && self.form.is_empty()
91 }
92
93 #[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 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}