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