use std::str::FromStr;
use chrono::{NaiveDate, NaiveDateTime};
use crate::form::{FieldErrors, FormInput};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FieldKind {
Text,
Textarea,
Password,
Number,
Decimal(&'static str),
Checkbox,
Select(&'static [(&'static str, &'static str)]),
Lookup,
Date,
DateTime,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Field {
pub name: &'static str,
pub label: &'static str,
pub kind: FieldKind,
pub required: bool,
}
impl Field {
pub fn check_required<'a>(
&self,
form: &'a FormInput,
errors: &mut FieldErrors,
) -> Option<&'a str> {
check_required(self.name, self.label, form, errors)
}
pub fn check_whole_number<T: FromStr>(
&self,
text: &str,
errors: &mut FieldErrors,
) -> Option<T> {
check_whole_number(self.name, self.label, text, errors)
}
pub fn check_number(&self, text: &str, errors: &mut FieldErrors) -> Option<f64> {
check_number(self.name, self.label, text, errors)
}
pub fn check_decimal<T: FromStr + Into<f64> + Copy>(
&self,
text: &str,
errors: &mut FieldErrors,
) -> Option<T> {
check_decimal(self.name, self.label, text, errors)
}
pub fn check_datetime(&self, text: &str, errors: &mut FieldErrors) -> Option<NaiveDateTime> {
check_datetime(self.name, self.label, text, errors)
}
pub fn check_choice(
&self,
text: &str,
choices: &[(&str, &str)],
errors: &mut FieldErrors,
) -> bool {
check_choice(self.name, text, choices, errors)
}
pub fn check_date(&self, text: &str, errors: &mut FieldErrors) -> Option<NaiveDate> {
check_date(self.name, self.label, text, errors)
}
}
pub(crate) fn check_required<'a>(
name: &str,
label: &str,
form: &'a FormInput,
errors: &mut FieldErrors,
) -> Option<&'a str> {
match form.get(name).map(str::trim) {
Some(value) if !value.is_empty() => Some(value),
_ => {
errors.insert(name.to_string(), format!("{label} is required."));
None
}
}
}
pub(crate) fn check_whole_number<T: FromStr>(
name: &str,
label: &str,
text: &str,
errors: &mut FieldErrors,
) -> Option<T> {
match text.parse::<T>() {
Ok(value) => Some(value),
Err(_) => {
errors.insert(name.to_string(), format!("{label} must be a whole number."));
None
}
}
}
pub(crate) fn check_number(
name: &str,
label: &str,
text: &str,
errors: &mut FieldErrors,
) -> Option<f64> {
match text.parse::<f64>() {
Ok(value) if value.is_finite() => Some(value),
_ => {
errors.insert(name.to_string(), format!("{label} must be a number."));
None
}
}
}
pub(crate) fn check_decimal<T: FromStr + Into<f64> + Copy>(
name: &str,
label: &str,
text: &str,
errors: &mut FieldErrors,
) -> Option<T> {
match text.parse::<T>() {
Ok(value) if Into::<f64>::into(value).is_finite() => Some(value),
_ => {
errors.insert(name.to_string(), format!("{label} must be a number."));
None
}
}
}
pub(crate) fn check_datetime(
name: &str,
label: &str,
text: &str,
errors: &mut FieldErrors,
) -> Option<NaiveDateTime> {
const FORMATS: [&str; 4] = [
"%Y-%m-%dT%H:%M",
"%Y-%m-%dT%H:%M:%S",
"%Y-%m-%d %H:%M",
"%Y-%m-%d %H:%M:%S",
];
let parsed = FORMATS
.iter()
.find_map(|format| NaiveDateTime::parse_from_str(text, format).ok());
if parsed.is_none() {
errors.insert(
name.to_string(),
format!("{label} must be a date and time, as YYYY-MM-DD HH:MM."),
);
}
parsed
}
pub(crate) fn check_choice(
name: &str,
text: &str,
choices: &[(&str, &str)],
errors: &mut FieldErrors,
) -> bool {
if choices.iter().any(|(value, _)| *value == text) {
return true;
}
errors.insert(name.to_string(), "Choose one of the options.".to_string());
false
}
pub(crate) fn check_date(
name: &str,
label: &str,
text: &str,
errors: &mut FieldErrors,
) -> Option<NaiveDate> {
match NaiveDate::parse_from_str(text, "%Y-%m-%d") {
Ok(value) => Some(value),
Err(_) => {
errors.insert(
name.to_string(),
format!("{label} must be a date, as YYYY-MM-DD."),
);
None
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Column {
pub key: &'static str,
pub label: &'static str,
pub sortable: bool,
pub searchable: bool,
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::HashMap;
const TITLE: Field = Field {
name: "title",
label: "Title",
kind: FieldKind::Text,
required: true,
};
fn form(pairs: &[(&str, &str)]) -> FormInput {
FormInput::new(
pairs
.iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect::<HashMap<_, _>>(),
)
}
#[test]
fn required_field_returns_trimmed_value() {
let mut errors = FieldErrors::new();
let input = form(&[("title", " Hello ")]);
assert_eq!(TITLE.check_required(&input, &mut errors), Some("Hello"));
assert!(errors.is_empty());
}
#[test]
fn missing_required_field_records_a_message() {
let mut errors = FieldErrors::new();
assert_eq!(TITLE.check_required(&form(&[]), &mut errors), None);
assert_eq!(
errors.get("title").map(String::as_str),
Some("Title is required.")
);
}
const PRICE: Field = Field {
name: "price",
label: "Price",
kind: FieldKind::Decimal("any"),
required: true,
};
const LAUNCH: Field = Field {
name: "launch",
label: "Launch",
kind: FieldKind::DateTime,
required: true,
};
#[test]
fn a_decimal_accepts_whole_and_fractional_numbers() {
let mut errors = FieldErrors::new();
assert_eq!(PRICE.check_decimal::<f64>("9.5", &mut errors), Some(9.5));
assert_eq!(PRICE.check_decimal::<f64>("-3", &mut errors), Some(-3.0));
assert_eq!(PRICE.check_decimal::<f32>("0.25", &mut errors), Some(0.25));
assert!(errors.is_empty());
}
#[test]
fn a_decimal_refuses_text_and_values_that_are_not_finite() {
for text in ["abc", "9,5", "NaN", "inf", ""] {
let mut errors = FieldErrors::new();
assert_eq!(
PRICE.check_decimal::<f64>(text, &mut errors),
None,
"{text}"
);
assert_eq!(
errors.get("price").map(String::as_str),
Some("Price must be a number."),
"{text}"
);
}
let mut errors = FieldErrors::new();
assert_eq!(PRICE.check_decimal::<f32>("1e300", &mut errors), None);
assert!(errors.contains_key("price"));
}
#[test]
fn a_datetime_accepts_the_input_format_with_or_without_seconds() {
let mut errors = FieldErrors::new();
let expected = chrono::NaiveDate::from_ymd_opt(2026, 11, 10)
.unwrap()
.and_hms_opt(14, 30, 0)
.unwrap();
assert_eq!(
LAUNCH.check_datetime("2026-11-10T14:30", &mut errors),
Some(expected)
);
assert_eq!(
LAUNCH.check_datetime("2026-11-10 14:30:00", &mut errors),
Some(expected)
);
assert!(errors.is_empty());
}
#[test]
fn a_datetime_refuses_what_is_not_a_date_and_time() {
for text in ["soon", "2026-11-10", "2026-13-40T10:00", "10/11/2026 14:30"] {
let mut errors = FieldErrors::new();
assert_eq!(LAUNCH.check_datetime(text, &mut errors), None, "{text}");
assert_eq!(
errors.get("launch").map(String::as_str),
Some("Launch must be a date and time, as YYYY-MM-DD HH:MM."),
"{text}"
);
}
}
#[test]
fn a_choice_must_be_one_of_the_choices() {
let choices = [("draft", "Draft"), ("published", "Published")];
let mut errors = FieldErrors::new();
assert!(TITLE.check_choice("draft", &choices, &mut errors));
assert!(errors.is_empty());
assert!(!TITLE.check_choice("archived", &choices, &mut errors));
assert_eq!(
errors.get("title").map(String::as_str),
Some("Choose one of the options.")
);
}
#[test]
fn blank_required_field_is_missing() {
let mut errors = FieldErrors::new();
assert_eq!(
TITLE.check_required(&form(&[("title", " ")]), &mut errors),
None
);
assert!(errors.contains_key("title"));
}
}