1use std::str::FromStr;
4
5use chrono::{NaiveDate, NaiveDateTime};
6
7use crate::form::{FieldErrors, FormInput};
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum FieldKind {
12 Text,
14 Textarea,
16 Password,
18 Number,
21 Decimal(&'static str),
24 Checkbox,
26 Select(&'static [(&'static str, &'static str)]),
28 Lookup,
32 Date,
34 DateTime,
36}
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub struct Field {
41 pub name: &'static str,
43 pub label: &'static str,
45 pub kind: FieldKind,
47 pub required: bool,
49}
50
51impl Field {
52 pub fn check_required<'a>(
56 &self,
57 form: &'a FormInput,
58 errors: &mut FieldErrors,
59 ) -> Option<&'a str> {
60 check_required(self.name, self.label, form, errors)
61 }
62
63 pub fn check_whole_number<T: FromStr>(
67 &self,
68 text: &str,
69 errors: &mut FieldErrors,
70 ) -> Option<T> {
71 check_whole_number(self.name, self.label, text, errors)
72 }
73
74 pub fn check_number(&self, text: &str, errors: &mut FieldErrors) -> Option<f64> {
78 check_number(self.name, self.label, text, errors)
79 }
80
81 pub fn check_decimal<T: FromStr + Into<f64> + Copy>(
85 &self,
86 text: &str,
87 errors: &mut FieldErrors,
88 ) -> Option<T> {
89 check_decimal(self.name, self.label, text, errors)
90 }
91
92 pub fn check_datetime(&self, text: &str, errors: &mut FieldErrors) -> Option<NaiveDateTime> {
97 check_datetime(self.name, self.label, text, errors)
98 }
99
100 pub fn check_choice(
103 &self,
104 text: &str,
105 choices: &[(&str, &str)],
106 errors: &mut FieldErrors,
107 ) -> bool {
108 check_choice(self.name, text, choices, errors)
109 }
110
111 pub fn check_date(&self, text: &str, errors: &mut FieldErrors) -> Option<NaiveDate> {
114 check_date(self.name, self.label, text, errors)
115 }
116}
117
118pub(crate) fn check_required<'a>(
123 name: &str,
124 label: &str,
125 form: &'a FormInput,
126 errors: &mut FieldErrors,
127) -> Option<&'a str> {
128 match form.get(name).map(str::trim) {
129 Some(value) if !value.is_empty() => Some(value),
130 _ => {
131 errors.insert(name.to_string(), format!("{label} is required."));
132 None
133 }
134 }
135}
136
137pub(crate) fn check_whole_number<T: FromStr>(
139 name: &str,
140 label: &str,
141 text: &str,
142 errors: &mut FieldErrors,
143) -> Option<T> {
144 match text.parse::<T>() {
145 Ok(value) => Some(value),
146 Err(_) => {
147 errors.insert(name.to_string(), format!("{label} must be a whole number."));
148 None
149 }
150 }
151}
152
153pub(crate) fn check_number(
155 name: &str,
156 label: &str,
157 text: &str,
158 errors: &mut FieldErrors,
159) -> Option<f64> {
160 match text.parse::<f64>() {
161 Ok(value) if value.is_finite() => Some(value),
162 _ => {
163 errors.insert(name.to_string(), format!("{label} must be a number."));
164 None
165 }
166 }
167}
168
169pub(crate) fn check_decimal<T: FromStr + Into<f64> + Copy>(
171 name: &str,
172 label: &str,
173 text: &str,
174 errors: &mut FieldErrors,
175) -> Option<T> {
176 match text.parse::<T>() {
177 Ok(value) if Into::<f64>::into(value).is_finite() => Some(value),
178 _ => {
179 errors.insert(name.to_string(), format!("{label} must be a number."));
180 None
181 }
182 }
183}
184
185pub(crate) fn check_datetime(
187 name: &str,
188 label: &str,
189 text: &str,
190 errors: &mut FieldErrors,
191) -> Option<NaiveDateTime> {
192 const FORMATS: [&str; 4] = [
193 "%Y-%m-%dT%H:%M",
194 "%Y-%m-%dT%H:%M:%S",
195 "%Y-%m-%d %H:%M",
196 "%Y-%m-%d %H:%M:%S",
197 ];
198 let parsed = FORMATS
199 .iter()
200 .find_map(|format| NaiveDateTime::parse_from_str(text, format).ok());
201 if parsed.is_none() {
202 errors.insert(
203 name.to_string(),
204 format!("{label} must be a date and time, as YYYY-MM-DD HH:MM."),
205 );
206 }
207 parsed
208}
209
210pub(crate) fn check_choice(
212 name: &str,
213 text: &str,
214 choices: &[(&str, &str)],
215 errors: &mut FieldErrors,
216) -> bool {
217 if choices.iter().any(|(value, _)| *value == text) {
218 return true;
219 }
220 errors.insert(name.to_string(), "Choose one of the options.".to_string());
221 false
222}
223
224pub(crate) fn check_date(
226 name: &str,
227 label: &str,
228 text: &str,
229 errors: &mut FieldErrors,
230) -> Option<NaiveDate> {
231 match NaiveDate::parse_from_str(text, "%Y-%m-%d") {
232 Ok(value) => Some(value),
233 Err(_) => {
234 errors.insert(
235 name.to_string(),
236 format!("{label} must be a date, as YYYY-MM-DD."),
237 );
238 None
239 }
240 }
241}
242
243#[derive(Debug, Clone, Copy, PartialEq, Eq)]
245pub struct Column {
246 pub key: &'static str,
248 pub label: &'static str,
250 pub sortable: bool,
252 pub searchable: bool,
254}
255
256#[cfg(test)]
257mod tests {
258 use super::*;
259 use std::collections::HashMap;
260
261 const TITLE: Field = Field {
262 name: "title",
263 label: "Title",
264 kind: FieldKind::Text,
265 required: true,
266 };
267
268 fn form(pairs: &[(&str, &str)]) -> FormInput {
269 FormInput::new(
270 pairs
271 .iter()
272 .map(|(k, v)| (k.to_string(), v.to_string()))
273 .collect::<HashMap<_, _>>(),
274 )
275 }
276
277 #[test]
278 fn required_field_returns_trimmed_value() {
279 let mut errors = FieldErrors::new();
280 let input = form(&[("title", " Hello ")]);
281
282 assert_eq!(TITLE.check_required(&input, &mut errors), Some("Hello"));
283 assert!(errors.is_empty());
284 }
285
286 #[test]
287 fn missing_required_field_records_a_message() {
288 let mut errors = FieldErrors::new();
289
290 assert_eq!(TITLE.check_required(&form(&[]), &mut errors), None);
291 assert_eq!(
292 errors.get("title").map(String::as_str),
293 Some("Title is required.")
294 );
295 }
296
297 const PRICE: Field = Field {
298 name: "price",
299 label: "Price",
300 kind: FieldKind::Decimal("any"),
301 required: true,
302 };
303
304 const LAUNCH: Field = Field {
305 name: "launch",
306 label: "Launch",
307 kind: FieldKind::DateTime,
308 required: true,
309 };
310
311 #[test]
312 fn a_decimal_accepts_whole_and_fractional_numbers() {
313 let mut errors = FieldErrors::new();
314
315 assert_eq!(PRICE.check_decimal::<f64>("9.5", &mut errors), Some(9.5));
316 assert_eq!(PRICE.check_decimal::<f64>("-3", &mut errors), Some(-3.0));
317 assert_eq!(PRICE.check_decimal::<f32>("0.25", &mut errors), Some(0.25));
318 assert!(errors.is_empty());
319 }
320
321 #[test]
322 fn a_decimal_refuses_text_and_values_that_are_not_finite() {
323 for text in ["abc", "9,5", "NaN", "inf", ""] {
324 let mut errors = FieldErrors::new();
325 assert_eq!(
326 PRICE.check_decimal::<f64>(text, &mut errors),
327 None,
328 "{text}"
329 );
330 assert_eq!(
331 errors.get("price").map(String::as_str),
332 Some("Price must be a number."),
333 "{text}"
334 );
335 }
336 let mut errors = FieldErrors::new();
337 assert_eq!(PRICE.check_decimal::<f32>("1e300", &mut errors), None);
338 assert!(errors.contains_key("price"));
339 }
340
341 #[test]
342 fn a_datetime_accepts_the_input_format_with_or_without_seconds() {
343 let mut errors = FieldErrors::new();
344 let expected = chrono::NaiveDate::from_ymd_opt(2026, 11, 10)
345 .unwrap()
346 .and_hms_opt(14, 30, 0)
347 .unwrap();
348
349 assert_eq!(
350 LAUNCH.check_datetime("2026-11-10T14:30", &mut errors),
351 Some(expected)
352 );
353 assert_eq!(
354 LAUNCH.check_datetime("2026-11-10 14:30:00", &mut errors),
355 Some(expected)
356 );
357 assert!(errors.is_empty());
358 }
359
360 #[test]
361 fn a_datetime_refuses_what_is_not_a_date_and_time() {
362 for text in ["soon", "2026-11-10", "2026-13-40T10:00", "10/11/2026 14:30"] {
363 let mut errors = FieldErrors::new();
364 assert_eq!(LAUNCH.check_datetime(text, &mut errors), None, "{text}");
365 assert_eq!(
366 errors.get("launch").map(String::as_str),
367 Some("Launch must be a date and time, as YYYY-MM-DD HH:MM."),
368 "{text}"
369 );
370 }
371 }
372
373 #[test]
374 fn a_choice_must_be_one_of_the_choices() {
375 let choices = [("draft", "Draft"), ("published", "Published")];
376 let mut errors = FieldErrors::new();
377
378 assert!(TITLE.check_choice("draft", &choices, &mut errors));
379 assert!(errors.is_empty());
380 assert!(!TITLE.check_choice("archived", &choices, &mut errors));
381 assert_eq!(
382 errors.get("title").map(String::as_str),
383 Some("Choose one of the options.")
384 );
385 }
386
387 #[test]
388 fn blank_required_field_is_missing() {
389 let mut errors = FieldErrors::new();
390
391 assert_eq!(
392 TITLE.check_required(&form(&[("title", " ")]), &mut errors),
393 None
394 );
395 assert!(errors.contains_key("title"));
396 }
397}