Skip to main content

ignite_core/
field.rs

1//! Form fields and table columns, as the panel renders them.
2
3use std::str::FromStr;
4
5use chrono::{NaiveDate, NaiveDateTime};
6
7use crate::form::{FieldErrors, FormInput};
8
9/// The kind of input a form field renders as, and how its value is read.
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
11pub enum FieldKind {
12    /// A single line of text.
13    Text,
14    /// Several lines of text.
15    Textarea,
16    /// A password. The form never shows the stored value.
17    Password,
18    /// A whole number, submitted as text. A resource's integer field is checked as a whole
19    /// number. A profile field accepts decimals as well (see [`Field::check_number`]).
20    Number,
21    /// A decimal number, submitted as text, such as `9.5`. The string is the browser's
22    /// step for the input: `"any"` accepts every value, and `"0.01"` steps by cents.
23    Decimal(&'static str),
24    /// A yes/no value. Read it with [`FormInput::checkbox`](crate::FormInput::checkbox).
25    Checkbox,
26    /// One choice from a list of `(value, label)` pairs.
27    Select(&'static [(&'static str, &'static str)]),
28    /// One choice from options that the resource loads from the database each time its
29    /// form is shown, such as the rows of a related table. See
30    /// [`IgniteResource::options`](crate::IgniteResource::options).
31    Lookup,
32    /// A calendar date, as `YYYY-MM-DD`.
33    Date,
34    /// A date and time, as `YYYY-MM-DDTHH:MM`, with seconds when given.
35    DateTime,
36    /// An email address, as Filament's `TextInput::make()->email()`. The value must be a
37    /// valid address, as the browser's `type="email"` input defines one (see
38    /// [`Field::check_email`]).
39    Email,
40    /// A URL, as Filament's `TextInput::make()->url()`. The value must parse as an absolute
41    /// URL (see [`Field::check_url`]).
42    Url,
43    /// One choice from a list of `(value, label)` pairs, shown as radio buttons, as
44    /// Filament's `Radio`. The value is checked as a [`Select`](Self::Select) is.
45    Radio(&'static [(&'static str, &'static str)]),
46    /// A color, as Filament's `ColorPicker`. The value is `#rrggbb`, stored in lowercase
47    /// (see [`Field::check_color`]).
48    Color,
49    /// An image from the media library, as Filament's `FileUpload::make()->image()`. The
50    /// value is the item's id, a positive whole number, stored as text. The panel shows the
51    /// item through the app's [`MediaLibrary`](crate::MediaLibrary), when one is registered.
52    Image,
53    /// A file from the media library, as Filament's `FileUpload`. Stored as
54    /// [`Image`](Self::Image) is.
55    File,
56    /// A link (ACF's link field): the JSON text `{"url": ..., "title": ..., "target": ...}`.
57    /// The URL is required and must parse; `target` is `""` or `"_blank"` (see
58    /// [`Field::check_link`]).
59    Link,
60    /// Rich text, as Filament's `RichEditor`. The panel renders a textarea marked with
61    /// `data-ignite-editor`, and loads the editor script the app registers with
62    /// [`register_editor`](crate::register_editor). Ignite bundles no editor. The value is
63    /// the submitted HTML, unchanged.
64    Wysiwyg,
65    /// One post, chosen from options loaded each time the form is shown, as a
66    /// [`Lookup`](Self::Lookup) is (ACF's post object field).
67    PostObject,
68    /// Several choices from options loaded each time the form is shown (ACF's relationship
69    /// field): the multi-value [`PostObject`](Self::PostObject). The value is a JSON array
70    /// of the chosen option values, as strings, such as `["12","40"]`.
71    Relationship,
72    /// One taxonomy term, chosen from loaded options, as a [`Lookup`](Self::Lookup) is.
73    Taxonomy,
74    /// One user, chosen from loaded options, as a [`Lookup`](Self::Lookup) is.
75    User,
76    /// Rows of the given sub-fields, as Filament's `Repeater`. The value is a JSON array
77    /// with one object per row, keyed by sub-field name, such as
78    /// `[{"title": "One"}, {"title": "Two"}]`. Each row is checked against the sub-fields.
79    Repeater(&'static [Field]),
80    /// The given sub-fields, kept together (ACF's group field). The value is one JSON
81    /// object keyed by sub-field name.
82    Group(&'static [Field]),
83    /// Rows that each take one of the given blocks, as Filament's `Builder`. The value is a
84    /// JSON array of `{"type": <block name>, "data": {<sub-field values>}}` objects, as
85    /// Filament stores a builder.
86    FlexibleContent(&'static [Block]),
87    /// Several images from the media library (ACF's gallery field). The value is a JSON
88    /// array of item ids, such as `[3,8]`.
89    Gallery,
90    /// The fields of another field group, reused (ACF's clone field). Ignite has no field
91    /// groups of its own: the app resolves the group it clones and passes its fields here.
92    /// The value is stored and checked as a [`Group`](Self::Group) of those fields is.
93    Clone(&'static [Field]),
94}
95
96impl FieldKind {
97    /// Whether the field's choices are loaded each time its form is shown, through
98    /// [`IgniteResource::options`](crate::IgniteResource::options) or
99    /// [`RuntimeData::options`](crate::RuntimeData::options): a lookup, post object,
100    /// relationship, taxonomy or user field.
101    pub fn loads_options(&self) -> bool {
102        matches!(
103            self,
104            FieldKind::Lookup
105                | FieldKind::PostObject
106                | FieldKind::Relationship
107                | FieldKind::Taxonomy
108                | FieldKind::User
109        )
110    }
111}
112
113/// One block of a [`FieldKind::FlexibleContent`] field, as Filament's `Builder\Block` (an
114/// ACF flexible content layout): a name, a label, and its sub-fields.
115#[derive(Debug, Clone, Copy, PartialEq, Eq)]
116pub struct Block {
117    /// The block's name, stored as the `type` of each row that uses it.
118    pub name: &'static str,
119    /// The label shown when choosing the block.
120    pub label: &'static str,
121    /// The block's sub-fields, in display order.
122    pub fields: &'static [Field],
123}
124
125/// One input on a create or edit form.
126#[derive(Debug, Clone, Copy, PartialEq, Eq)]
127pub struct Field {
128    /// The form field name. It matches a key of the record.
129    pub name: &'static str,
130    /// The label shown next to the input.
131    pub label: &'static str,
132    /// The input type, and how the value is read.
133    pub kind: FieldKind,
134    /// Whether the form rejects a blank value.
135    pub required: bool,
136}
137
138impl Field {
139    /// Returns the trimmed value of a required field. If it is missing or
140    /// blank, records "<label> is required" in `errors` under the field name
141    /// and returns `None`.
142    pub fn check_required<'a>(
143        &self,
144        form: &'a FormInput,
145        errors: &mut FieldErrors,
146    ) -> Option<&'a str> {
147        check_required(self.name, self.label, form, errors)
148    }
149
150    /// Parses `text` as a whole number of type `T`. If it does not parse, records
151    /// "<label> must be a whole number." in `errors` and returns `None`. Resources and
152    /// profile fields both check numbers this way.
153    pub fn check_whole_number<T: FromStr>(
154        &self,
155        text: &str,
156        errors: &mut FieldErrors,
157    ) -> Option<T> {
158        check_whole_number(self.name, self.label, text, errors)
159    }
160
161    /// Parses `text` as a number, whole or decimal, such as `42` or `42.5`. Values that are
162    /// not finite (`inf`, `NaN`) are refused. If it does not parse, records
163    /// "<label> must be a number." in `errors` and returns `None`.
164    pub fn check_number(&self, text: &str, errors: &mut FieldErrors) -> Option<f64> {
165        check_number(self.name, self.label, text, errors)
166    }
167
168    /// Parses `text` as a decimal number of type `T` (`f32` or `f64`), such as `9.5`. A
169    /// value that is not finite (`inf`, `NaN`, or an `f32` too large) is refused. If it
170    /// does not parse, records "<label> must be a number." in `errors` and returns `None`.
171    pub fn check_decimal<T: FromStr + Into<f64> + Copy>(
172        &self,
173        text: &str,
174        errors: &mut FieldErrors,
175    ) -> Option<T> {
176        check_decimal(self.name, self.label, text, errors)
177    }
178
179    /// Parses `text` as a date and time: `YYYY-MM-DDTHH:MM` as a date-time input sends it,
180    /// or with a space in place of the `T`, and with seconds when given. If it does not
181    /// parse, records "<label> must be a date and time, as YYYY-MM-DD HH:MM." in `errors`
182    /// and returns `None`.
183    pub fn check_datetime(&self, text: &str, errors: &mut FieldErrors) -> Option<NaiveDateTime> {
184        check_datetime(self.name, self.label, text, errors)
185    }
186
187    /// Checks that `text` is the value of one of `choices`. If it is not, records
188    /// "Choose one of the options." in `errors` and returns false.
189    pub fn check_choice(
190        &self,
191        text: &str,
192        choices: &[(&str, &str)],
193        errors: &mut FieldErrors,
194    ) -> bool {
195        check_choice(self.name, text, choices, errors)
196    }
197
198    /// Parses `text` as a `YYYY-MM-DD` date. If it does not parse, records
199    /// "<label> must be a date, as YYYY-MM-DD." in `errors` and returns `None`.
200    pub fn check_date(&self, text: &str, errors: &mut FieldErrors) -> Option<NaiveDate> {
201        check_date(self.name, self.label, text, errors)
202    }
203
204    /// Checks that `text`, trimmed, is an email address, as the browser's `type="email"`
205    /// input defines one: a local part of letters, digits and ``.!#$%&'*+/=?^_`{|}~-``, an
206    /// `@`, and a domain of dot-separated labels of letters, digits and inner hyphens. If it
207    /// is not, records "<label> must be a valid email address." and returns `None`.
208    pub fn check_email(&self, text: &str, errors: &mut FieldErrors) -> Option<String> {
209        check_email(self.name, self.label, text, errors)
210    }
211
212    /// Checks that `text`, trimmed, is a URL as ACF's URL field accepts one: an absolute URL
213    /// that parses, such as `https://example.com/about`, or a protocol-relative one with a
214    /// host, such as `//cdn.example.com/lib.js`. The `javascript:`, `data:` and `vbscript:`
215    /// schemes are refused in any case and with any whitespace or control characters around
216    /// them, because a link to one runs code. Otherwise records "<label> must be a valid URL."
217    /// and returns `None`.
218    pub fn check_url(&self, text: &str, errors: &mut FieldErrors) -> Option<String> {
219        check_url(self.name, self.label, text, errors)
220    }
221
222    /// Checks that `text`, trimmed, is a color as `#rrggbb`, and returns it in lowercase. If
223    /// it is not, records "<label> must be a color, as #rrggbb." and returns `None`.
224    pub fn check_color(&self, text: &str, errors: &mut FieldErrors) -> Option<String> {
225        check_color(self.name, self.label, text, errors)
226    }
227
228    /// Checks that `text` is the JSON of a link, `{"url": ..., "title": ..., "target": ...}`,
229    /// whose target is `""` or `"_blank"` and whose URL is one ACF's link picker stores: a URL
230    /// that passes [`check_url`](Self::check_url), a root-relative path (`/about`), an anchor
231    /// (`#top`) or a query (`?a=b`). A blank URL, `//` with no host and a script scheme are
232    /// refused. The title and target may be left out. Returns the link as JSON text with
233    /// all three keys. Otherwise records "<label> must be a link with a valid URL." and
234    /// returns `None`.
235    pub fn check_link(&self, text: &str, errors: &mut FieldErrors) -> Option<String> {
236        check_link(self.name, self.label, text, errors)
237    }
238
239    /// Checks `text` against the field's kind, and returns the text to store, for the kinds
240    /// whose value is text: email, URL, radio, color, image, file, link, wysiwyg, post
241    /// object, relationship, taxonomy, user, repeater, group, flexible content, gallery and
242    /// clone. The structured kinds (relationship, repeater, group, flexible content, gallery,
243    /// clone) take JSON text, check each value against its sub-field, and return the checked
244    /// JSON; reading it back gives the same structure. An empty list or group is blank, so a
245    /// required field records "<label> is required.". A required field must first pass
246    /// [`check_required`](Self::check_required).
247    ///
248    /// The other kinds have checks of their own (such as
249    /// [`check_whole_number`](Self::check_whole_number)); for them `text` is returned
250    /// unchanged.
251    pub fn check_value(&self, text: &str, errors: &mut FieldErrors) -> Option<String> {
252        let kind = crate::FieldKindDef::from(self.kind);
253        crate::value::check_value(self.name, self.label, self.required, &kind, text, errors)
254    }
255}
256
257// The checks themselves, by field name and label, so a static `Field` and a runtime
258// `FieldDef` run the same code. `name` is the key of the error in `errors`.
259
260/// See [`Field::check_required`].
261pub(crate) fn check_required<'a>(
262    name: &str,
263    label: &str,
264    form: &'a FormInput,
265    errors: &mut FieldErrors,
266) -> Option<&'a str> {
267    match form.get(name).map(str::trim) {
268        Some(value) if !value.is_empty() => Some(value),
269        _ => {
270            errors.insert(name.to_string(), format!("{label} is required."));
271            None
272        }
273    }
274}
275
276/// See [`Field::check_whole_number`].
277pub(crate) fn check_whole_number<T: FromStr>(
278    name: &str,
279    label: &str,
280    text: &str,
281    errors: &mut FieldErrors,
282) -> Option<T> {
283    match text.parse::<T>() {
284        Ok(value) => Some(value),
285        Err(_) => {
286            errors.insert(name.to_string(), format!("{label} must be a whole number."));
287            None
288        }
289    }
290}
291
292/// See [`Field::check_number`].
293pub(crate) fn check_number(
294    name: &str,
295    label: &str,
296    text: &str,
297    errors: &mut FieldErrors,
298) -> Option<f64> {
299    match text.parse::<f64>() {
300        Ok(value) if value.is_finite() => Some(value),
301        _ => {
302            errors.insert(name.to_string(), format!("{label} must be a number."));
303            None
304        }
305    }
306}
307
308/// See [`Field::check_decimal`].
309pub(crate) fn check_decimal<T: FromStr + Into<f64> + Copy>(
310    name: &str,
311    label: &str,
312    text: &str,
313    errors: &mut FieldErrors,
314) -> Option<T> {
315    match text.parse::<T>() {
316        Ok(value) if Into::<f64>::into(value).is_finite() => Some(value),
317        _ => {
318            errors.insert(name.to_string(), format!("{label} must be a number."));
319            None
320        }
321    }
322}
323
324/// See [`Field::check_datetime`].
325pub(crate) fn check_datetime(
326    name: &str,
327    label: &str,
328    text: &str,
329    errors: &mut FieldErrors,
330) -> Option<NaiveDateTime> {
331    const FORMATS: [&str; 4] = [
332        "%Y-%m-%dT%H:%M",
333        "%Y-%m-%dT%H:%M:%S",
334        "%Y-%m-%d %H:%M",
335        "%Y-%m-%d %H:%M:%S",
336    ];
337    let parsed = FORMATS
338        .iter()
339        .find_map(|format| NaiveDateTime::parse_from_str(text, format).ok());
340    if parsed.is_none() {
341        errors.insert(
342            name.to_string(),
343            format!("{label} must be a date and time, as YYYY-MM-DD HH:MM."),
344        );
345    }
346    parsed
347}
348
349/// See [`Field::check_choice`].
350pub(crate) fn check_choice(
351    name: &str,
352    text: &str,
353    choices: &[(&str, &str)],
354    errors: &mut FieldErrors,
355) -> bool {
356    if choices.iter().any(|(value, _)| *value == text) {
357        return true;
358    }
359    errors.insert(name.to_string(), "Choose one of the options.".to_string());
360    false
361}
362
363/// See [`Field::check_date`].
364pub(crate) fn check_date(
365    name: &str,
366    label: &str,
367    text: &str,
368    errors: &mut FieldErrors,
369) -> Option<NaiveDate> {
370    match NaiveDate::parse_from_str(text, "%Y-%m-%d") {
371        Ok(value) => Some(value),
372        Err(_) => {
373            errors.insert(
374                name.to_string(),
375                format!("{label} must be a date, as YYYY-MM-DD."),
376            );
377            None
378        }
379    }
380}
381
382/// See [`Field::check_email`].
383pub(crate) fn check_email(
384    name: &str,
385    label: &str,
386    text: &str,
387    errors: &mut FieldErrors,
388) -> Option<String> {
389    let text = text.trim();
390    if is_email(text) {
391        return Some(text.to_string());
392    }
393    errors.insert(
394        name.to_string(),
395        format!("{label} must be a valid email address."),
396    );
397    None
398}
399
400/// Whether `text` is a valid email address, as the HTML standard defines one for
401/// `<input type="email">`.
402pub(crate) fn is_email(text: &str) -> bool {
403    let Some((local, domain)) = text.split_once('@') else {
404        return false;
405    };
406    let local_ok = !local.is_empty()
407        && local
408            .bytes()
409            .all(|b| b.is_ascii_alphanumeric() || b".!#$%&'*+/=?^_`{|}~-".contains(&b));
410    let domain_ok = !domain.is_empty()
411        && domain.split('.').all(|part| {
412            !part.is_empty()
413                && part.len() <= 63
414                && !part.starts_with('-')
415                && !part.ends_with('-')
416                && part.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-')
417        });
418    local_ok && domain_ok
419}
420
421/// See [`Field::check_url`].
422pub(crate) fn check_url(
423    name: &str,
424    label: &str,
425    text: &str,
426    errors: &mut FieldErrors,
427) -> Option<String> {
428    let text = text.trim();
429    if is_url(text) {
430        return Some(text.to_string());
431    }
432    errors.insert(name.to_string(), format!("{label} must be a valid URL."));
433    None
434}
435
436/// Whether `text` is an absolute URL that parses, or a protocol-relative URL (`//host/...`)
437/// with a host, and its scheme cannot run code.
438pub(crate) fn is_url(text: &str) -> bool {
439    if has_script_scheme(text) {
440        return false;
441    }
442    if let Some(rest) = text.strip_prefix("//") {
443        // `//` must be followed by a host: not by another slash, which a browser skips.
444        if rest.is_empty() || rest.starts_with(['/', '\\']) {
445            return false;
446        }
447        return url::Url::parse(&format!("https:{text}"))
448            .is_ok_and(|url| url.host_str().is_some_and(|host| !host.is_empty()));
449    }
450    match url::Url::parse(text) {
451        Ok(url) => !matches!(url.scheme(), "javascript" | "data" | "vbscript"),
452        Err(_) => false,
453    }
454}
455
456/// Whether `text` is a link target as ACF's link picker stores one: a URL that passes
457/// [`is_url`], a root-relative path (`/about`), an anchor (`#top`) or a query (`?a=b`). A
458/// path may not start with `//` or `/\`, which a browser reads as another host.
459pub(crate) fn is_link_url(text: &str) -> bool {
460    if is_url(text) {
461        return true;
462    }
463    let relative = match text.strip_prefix('/') {
464        Some(rest) => !rest.starts_with(['/', '\\']),
465        None => text.starts_with(['#', '?']),
466    };
467    relative && !text.chars().any(|c| c.is_control() || c.is_whitespace())
468}
469
470/// Whether `text` starts with the `javascript:`, `data:` or `vbscript:` scheme, in any case.
471/// Whitespace and control characters are ignored, as a browser strips them from a URL
472/// before it reads the scheme.
473fn has_script_scheme(text: &str) -> bool {
474    let scheme: String = text
475        .chars()
476        .filter(|c| !c.is_whitespace() && !c.is_control())
477        .take_while(|c| *c != ':')
478        .collect::<String>()
479        .to_ascii_lowercase();
480    let has_colon = text.contains(':');
481    has_colon && matches!(scheme.as_str(), "javascript" | "data" | "vbscript")
482}
483
484/// See [`Field::check_color`].
485pub(crate) fn check_color(
486    name: &str,
487    label: &str,
488    text: &str,
489    errors: &mut FieldErrors,
490) -> Option<String> {
491    let text = text.trim();
492    if is_color(text) {
493        return Some(text.to_ascii_lowercase());
494    }
495    errors.insert(
496        name.to_string(),
497        format!("{label} must be a color, as #rrggbb."),
498    );
499    None
500}
501
502/// Whether `text` is a color as `#rrggbb`, in either case.
503pub(crate) fn is_color(text: &str) -> bool {
504    text.len() == 7 && text.starts_with('#') && text[1..].bytes().all(|b| b.is_ascii_hexdigit())
505}
506
507/// See [`Field::check_link`].
508pub(crate) fn check_link(
509    name: &str,
510    label: &str,
511    text: &str,
512    errors: &mut FieldErrors,
513) -> Option<String> {
514    let link = serde_json::from_str::<serde_json::Value>(text)
515        .ok()
516        .and_then(|value| link_value(&value));
517    match link {
518        Some(link) => Some(link.to_string()),
519        None => {
520            errors.insert(
521                name.to_string(),
522                format!("{label} must be a link with a valid URL."),
523            );
524            None
525        }
526    }
527}
528
529/// The link in `value`, with its three keys, if it is a link object whose URL is valid and
530/// whose target is `""` or `"_blank"`.
531pub(crate) fn link_value(value: &serde_json::Value) -> Option<serde_json::Value> {
532    let object = value.as_object()?;
533    let text = |key: &str| match object.get(key) {
534        None | Some(serde_json::Value::Null) => Some(String::new()),
535        Some(serde_json::Value::String(text)) => Some(text.trim().to_string()),
536        Some(_) => None,
537    };
538    let url = text("url")?;
539    let title = text("title")?;
540    let target = text("target")?;
541    if !is_link_url(&url) || !matches!(target.as_str(), "" | "_blank") {
542        return None;
543    }
544    Some(serde_json::json!({ "url": url, "title": title, "target": target }))
545}
546
547/// One column of the list view.
548#[derive(Debug, Clone, Copy, PartialEq, Eq)]
549pub struct Column {
550    /// The record key the column shows. It matches a field name.
551    pub key: &'static str,
552    /// The column heading.
553    pub label: &'static str,
554    /// Whether the heading links to a sort by this column.
555    pub sortable: bool,
556    /// Whether the search box matches this column.
557    pub searchable: bool,
558}
559
560#[cfg(test)]
561mod tests {
562    use super::*;
563    use std::collections::HashMap;
564
565    const TITLE: Field = Field {
566        name: "title",
567        label: "Title",
568        kind: FieldKind::Text,
569        required: true,
570    };
571
572    fn form(pairs: &[(&str, &str)]) -> FormInput {
573        FormInput::new(
574            pairs
575                .iter()
576                .map(|(k, v)| (k.to_string(), v.to_string()))
577                .collect::<HashMap<_, _>>(),
578        )
579    }
580
581    #[test]
582    fn required_field_returns_trimmed_value() {
583        let mut errors = FieldErrors::new();
584        let input = form(&[("title", "  Hello  ")]);
585
586        assert_eq!(TITLE.check_required(&input, &mut errors), Some("Hello"));
587        assert!(errors.is_empty());
588    }
589
590    #[test]
591    fn missing_required_field_records_a_message() {
592        let mut errors = FieldErrors::new();
593
594        assert_eq!(TITLE.check_required(&form(&[]), &mut errors), None);
595        assert_eq!(
596            errors.get("title").map(String::as_str),
597            Some("Title is required.")
598        );
599    }
600
601    const PRICE: Field = Field {
602        name: "price",
603        label: "Price",
604        kind: FieldKind::Decimal("any"),
605        required: true,
606    };
607
608    const LAUNCH: Field = Field {
609        name: "launch",
610        label: "Launch",
611        kind: FieldKind::DateTime,
612        required: true,
613    };
614
615    #[test]
616    fn a_decimal_accepts_whole_and_fractional_numbers() {
617        let mut errors = FieldErrors::new();
618
619        assert_eq!(PRICE.check_decimal::<f64>("9.5", &mut errors), Some(9.5));
620        assert_eq!(PRICE.check_decimal::<f64>("-3", &mut errors), Some(-3.0));
621        assert_eq!(PRICE.check_decimal::<f32>("0.25", &mut errors), Some(0.25));
622        assert!(errors.is_empty());
623    }
624
625    #[test]
626    fn a_decimal_refuses_text_and_values_that_are_not_finite() {
627        for text in ["abc", "9,5", "NaN", "inf", ""] {
628            let mut errors = FieldErrors::new();
629            assert_eq!(
630                PRICE.check_decimal::<f64>(text, &mut errors),
631                None,
632                "{text}"
633            );
634            assert_eq!(
635                errors.get("price").map(String::as_str),
636                Some("Price must be a number."),
637                "{text}"
638            );
639        }
640        let mut errors = FieldErrors::new();
641        assert_eq!(PRICE.check_decimal::<f32>("1e300", &mut errors), None);
642        assert!(errors.contains_key("price"));
643    }
644
645    #[test]
646    fn a_datetime_accepts_the_input_format_with_or_without_seconds() {
647        let mut errors = FieldErrors::new();
648        let expected = chrono::NaiveDate::from_ymd_opt(2026, 11, 10)
649            .unwrap()
650            .and_hms_opt(14, 30, 0)
651            .unwrap();
652
653        assert_eq!(
654            LAUNCH.check_datetime("2026-11-10T14:30", &mut errors),
655            Some(expected)
656        );
657        assert_eq!(
658            LAUNCH.check_datetime("2026-11-10 14:30:00", &mut errors),
659            Some(expected)
660        );
661        assert!(errors.is_empty());
662    }
663
664    #[test]
665    fn a_datetime_refuses_what_is_not_a_date_and_time() {
666        for text in ["soon", "2026-11-10", "2026-13-40T10:00", "10/11/2026 14:30"] {
667            let mut errors = FieldErrors::new();
668            assert_eq!(LAUNCH.check_datetime(text, &mut errors), None, "{text}");
669            assert_eq!(
670                errors.get("launch").map(String::as_str),
671                Some("Launch must be a date and time, as YYYY-MM-DD HH:MM."),
672                "{text}"
673            );
674        }
675    }
676
677    #[test]
678    fn a_choice_must_be_one_of_the_choices() {
679        let choices = [("draft", "Draft"), ("published", "Published")];
680        let mut errors = FieldErrors::new();
681
682        assert!(TITLE.check_choice("draft", &choices, &mut errors));
683        assert!(errors.is_empty());
684        assert!(!TITLE.check_choice("archived", &choices, &mut errors));
685        assert_eq!(
686            errors.get("title").map(String::as_str),
687            Some("Choose one of the options.")
688        );
689    }
690
691    #[test]
692    fn blank_required_field_is_missing() {
693        let mut errors = FieldErrors::new();
694
695        assert_eq!(
696            TITLE.check_required(&form(&[("title", "   ")]), &mut errors),
697            None
698        );
699        assert!(errors.contains_key("title"));
700    }
701}