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