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
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
//! Email field with validation
use crate::field::{FieldError, FieldResult, FormField, Widget};
use regex::Regex;
use std::sync::LazyLock;
const EMAIL_PATTERN: &str = r"^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$";
static EMAIL_REGEX: LazyLock<Regex> =
LazyLock::new(|| Regex::new(EMAIL_PATTERN).expect("Email regex pattern is valid"));
/// Email field with format validation
#[derive(Debug, Clone)]
pub struct EmailField {
/// The field name used as the form data key.
pub name: String,
/// Optional human-readable label for display.
pub label: Option<String>,
/// Whether this field must be filled in.
pub required: bool,
/// Optional help text displayed alongside the field.
pub help_text: Option<String>,
/// The widget type used for rendering this field.
pub widget: Widget,
/// Optional initial (default) value for the field.
pub initial: Option<serde_json::Value>,
/// Maximum allowed character count (defaults to 320 per RFC).
pub max_length: Option<usize>,
/// Minimum required character count.
pub min_length: Option<usize>,
}
impl EmailField {
/// Create a new EmailField with the given name
///
/// # Examples
///
/// ```
/// use reinhardt_forms::fields::EmailField;
///
/// let field = EmailField::new("email".to_string());
/// assert_eq!(field.name, "email");
/// assert!(!field.required);
/// assert_eq!(field.max_length, Some(320));
/// ```
pub fn new(name: String) -> Self {
Self {
name,
label: None,
required: false,
help_text: None,
widget: Widget::EmailInput,
initial: None,
max_length: Some(320), // RFC standard: 64 (local) + @ + 255 (domain)
min_length: None,
}
}
/// Set the field as required
///
/// # Examples
///
/// ```
/// use reinhardt_forms::fields::EmailField;
///
/// let field = EmailField::new("contact".to_string()).required();
/// assert!(field.required);
/// ```
pub fn required(mut self) -> Self {
self.required = true;
self
}
/// Set the maximum length for the field
///
/// # Examples
///
/// ```
/// use reinhardt_forms::fields::EmailField;
///
/// let field = EmailField::new("email".to_string()).with_max_length(100);
/// assert_eq!(field.max_length, Some(100));
/// ```
pub fn with_max_length(mut self, max_length: usize) -> Self {
self.max_length = Some(max_length);
self
}
/// Set the minimum length for the field
///
/// # Examples
///
/// ```
/// use reinhardt_forms::fields::EmailField;
///
/// let field = EmailField::new("email".to_string()).with_min_length(5);
/// assert_eq!(field.min_length, Some(5));
/// ```
pub fn with_min_length(mut self, min_length: usize) -> Self {
self.min_length = Some(min_length);
self
}
/// Set the label for the field
///
/// # Examples
///
/// ```
/// use reinhardt_forms::fields::EmailField;
///
/// let field = EmailField::new("contact_email".to_string()).with_label("Email Address");
/// assert_eq!(field.label, Some("Email Address".to_string()));
/// ```
pub fn with_label(mut self, label: impl Into<String>) -> Self {
self.label = Some(label.into());
self
}
/// Set the help text for the field
///
/// # Examples
///
/// ```
/// use reinhardt_forms::fields::EmailField;
///
/// let field = EmailField::new("email".to_string()).with_help_text("We'll never share your email");
/// assert_eq!(field.help_text, Some("We'll never share your email".to_string()));
/// ```
pub fn with_help_text(mut self, help_text: impl Into<String>) -> Self {
self.help_text = Some(help_text.into());
self
}
/// Set the initial value for the field
///
/// # Examples
///
/// ```
/// use reinhardt_forms::fields::EmailField;
///
/// let field = EmailField::new("email".to_string()).with_initial("user@example.com");
/// assert_eq!(field.initial, Some(serde_json::json!("user@example.com")));
/// ```
pub fn with_initial(mut self, initial: impl Into<String>) -> Self {
self.initial = Some(serde_json::json!(initial.into()));
self
}
/// Validate email format
fn validate_email(email: &str) -> bool {
EMAIL_REGEX.is_match(email)
}
}
// Note: Default trait is not implemented because EmailField requires a name
impl FormField for EmailField {
fn name(&self) -> &str {
&self.name
}
fn label(&self) -> Option<&str> {
self.label.as_deref()
}
fn required(&self) -> bool {
self.required
}
fn help_text(&self) -> Option<&str> {
self.help_text.as_deref()
}
fn widget(&self) -> &Widget {
&self.widget
}
fn initial(&self) -> Option<&serde_json::Value> {
self.initial.as_ref()
}
fn clean(&self, value: Option<&serde_json::Value>) -> FieldResult<serde_json::Value> {
match value {
None if self.required => Err(FieldError::Required(self.name.clone())),
None => Ok(serde_json::Value::String(String::new())),
Some(v) => {
let s = v
.as_str()
.ok_or_else(|| FieldError::Validation("Expected string".to_string()))?;
let s = s.trim();
// Return empty string if not required and empty
if s.is_empty() {
if self.required {
return Err(FieldError::Required(self.name.clone()));
}
return Ok(serde_json::Value::String(String::new()));
}
// Check length constraints using character count (not byte count)
// for correct multi-byte character handling
let char_count = s.chars().count();
if let Some(max) = self.max_length
&& char_count > max
{
return Err(FieldError::Validation(format!(
"Ensure this value has at most {} characters (it has {})",
max, char_count
)));
}
if let Some(min) = self.min_length
&& char_count < min
{
return Err(FieldError::Validation(format!(
"Ensure this value has at least {} characters (it has {})",
min, char_count
)));
}
// Validate email format
if !Self::validate_email(s) {
return Err(FieldError::Validation(
"Enter a valid email address".to_string(),
));
}
Ok(serde_json::Value::String(s.to_string()))
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use rstest::rstest;
#[rstest]
fn direct_email_field_strips_by_default() {
let field = EmailField::new("email".to_owned());
assert_eq!(
field
.clean(Some(&serde_json::json!(" person@example.com ")))
.unwrap(),
serde_json::json!("person@example.com")
);
}
#[rstest]
fn direct_email_field_preserves_its_legacy_localhost_compatibility() {
let field = EmailField::new("email".to_owned());
assert_eq!(
field
.clean(Some(&serde_json::json!("person@localhost")))
.unwrap(),
serde_json::json!("person@localhost")
);
}
#[rstest]
#[case(None)]
#[case(Some(serde_json::json!(" ")))]
fn required_email_field_preserves_the_legacy_field_name_message(
#[case] value: Option<serde_json::Value>,
) {
let field = EmailField::new("email".to_owned()).required();
assert_eq!(
field.clean(value.as_ref()).unwrap_err().to_string(),
"email"
);
}
}