use super::form_date_parts::{validate_date_parts, DateParts, DateRules}; use super::funejson::Value; // ASCII whitespace only, so all three languages trim the same characters. fn trim_ascii(value: &str) -> &str { value.trim_matches(|c: char| matches!(c, ' ' | '\t' | '\n' | '\r' | '\x0c' | '\x0b')) } // YYYY-MM-DD with ASCII digits: what submits, and nothing // else (no time, no offset, no other script's digits). fn iso_shape(value: &str) -> bool { let bytes = value.as_bytes(); bytes.len() == 10 && bytes.iter().enumerate().all(|(i, &b)| if i == 4 || i == 7 { b == b'-' } else { b.is_ascii_digit() }) } /// A date picker's value, checked with form.date-parts' rules and messages. /// Pure calendar arithmetic on the string, so no time zone can move the day; /// "today" for past/future rules is passed in by the caller. /// /// # Panics /// As form.date-parts: an empty label, a timing rule without today, a /// malformed rule date, or notBefore after notAfter. pub fn validate_iso_date(value: &str, label: &str, required: bool, rules: &DateRules) -> IsoDateCheck { // Called with empty boxes first, so a bad label or bad rules panic // whatever was typed, and its answer is the "Enter ..." message. let empty = DateParts { day: String::new(), month: String::new(), year: String::new() }; let blank = validate_date_parts(&empty, label, rules); let typed = trim_ascii(value); if typed.is_empty() { return if required { IsoDateCheck { valid: false, date: None, message: blank.message } } else { IsoDateCheck { valid: true, date: None, message: None } }; } if !iso_shape(typed) { return IsoDateCheck { valid: false, date: None, message: Some(format!("{} must be a real date", trim_ascii(label))) }; } let parts = DateParts { day: typed[8..10].to_string(), month: typed[5..7].to_string(), year: typed[0..4].to_string() }; let check = validate_date_parts(&parts, label, rules); if check.valid { IsoDateCheck { valid: true, date: check.date, message: None } } else { IsoDateCheck { valid: false, date: None, message: check.message } } } pub fn iso_date_check_to_value(check: &IsoDateCheck) -> Value { let text = |v: &Option| v.as_deref().map(Value::str).unwrap_or(Value::Null); Value::obj(vec![("valid", Value::Bool(check.valid)), ("date", text(&check.date)), ("message", text(&check.message))]) } pub fn fune_vector(args: &[Value]) -> Value { let optional = |v: &Value, key: &str| match v.get(key) { Value::Str(s) => Some(s.clone()), _ => None, }; let rules = DateRules { today: optional(&args[3], "today"), timing: optional(&args[3], "timing"), not_before: optional(&args[3], "notBefore"), not_after: optional(&args[3], "notAfter"), }; iso_date_check_to_value(&validate_iso_date(args[0].as_str(), args[1].as_str(), args[2].as_bool(), &rules)) }