Functional Weave
Code in TypeScript

form.iso-date@1.0.0

impl/typescript.ts

2,150 bytes · the TypeScript implementation · view raw

Imports name this capability’s declared dependencies, which fune builds next to it in your project; each one links to its page.

import { validateDateParts, type DateRules } from "./form_date_parts.ts";  ← from form.date-parts ^1.0.0 · built alongside by fune
import type { IsoDateCheck } from "./form_iso_date_types.ts";

// ASCII whitespace only, so all three languages trim the same characters.
function isSpace(ch: string): boolean {
  return ch === " " || ch === "\t" || ch === "\n" || ch === "\r" || ch === "\f" || ch === "\v";
}

function trim(value: string): string {
  let start = 0;
  let end = value.length;
  while (start < end && isSpace(value[start])) start++;
  while (end > start && isSpace(value[end - 1])) end--;
  return value.slice(start, end);
}

// YYYY-MM-DD with ASCII digits: what <input type="date"> submits, and nothing
// else (no time, no offset, no other script's digits).
function isoShape(value: string): boolean {
  if (value.length !== 10) return false;
  for (let i = 0; i < 10; i++) {
    const ch = value[i];
    if (i === 4 || i === 7) {
      if (ch !== "-") return false;
    } else if (ch < "0" || ch > "9") {
      return false;
    }
  }
  return true;
}

/**
 * A date picker's value, checked with form.date-parts' rules and messages.
 * Pure calendar arithmetic on the string: no Date object, so no time zone can
 * move the day; "today" for past/future rules is passed in by the caller.
 */
export function validateIsoDate(value: string, label: string, required: boolean, rules: DateRules): IsoDateCheck {
  // Called with empty boxes first, so a bad label or bad rules throw whatever
  // was typed, and its answer is the "Enter ..." message for a required date.
  const empty = validateDateParts({ day: "", month: "", year: "" }, label, rules);
  const typed = trim(value);
  if (typed === "") {
    return required ? { valid: false, date: null, message: empty.message } : { valid: true, date: null, message: null };
  }
  if (!isoShape(typed)) return { valid: false, date: null, message: `${trim(label)} must be a real date` };
  const check = validateDateParts({ day: typed.slice(8, 10), month: typed.slice(5, 7), year: typed.slice(0, 4) }, label, rules);
  return check.valid ? { valid: true, date: check.date, message: null } : { valid: false, date: null, message: check.message };
}