Functional Weave
Code in Rust

form.validate-input@1.0.0

impl/typescript.ts

6,550 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 { matchesPattern } from "./text_pattern_match.ts";  ← from text.pattern-match ^1.0.0 · built alongside by fune
import { isEmail } from "./validation_email.ts";  ← from validation.email ^1.0.0 · built alongside by fune
import type { InputCheck, InputRules } from "./form_validate_input_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);
}

// "Full name" starts a sentence; after "Enter" it is "full name". A label that
// starts with an acronym ("UK phone number") is left as it is.
function lowerFirst(label: string): string {
  const upper = (c: string | undefined) => c !== undefined && c >= "A" && c <= "Z";
  if (upper(label[0]) && !upper(label[1])) return label[0].toLowerCase() + label.slice(1);
  return label;
}

interface Decimal {
  negative: boolean;
  whole: string; // no leading zeros; "" for zero
  fraction: string; // no trailing zeros
}

function isDigits(s: string): boolean {
  if (s === "") return false;
  for (const ch of s) if (ch < "0" || ch > "9") return false;
  return true;
}

// -12, 12.5, .5 and 0.50: ASCII digits, one optional point, an optional
// leading minus. No exponent, no grouping, no plus: what a person types.
function parseDecimal(text: string, integer: boolean): Decimal | null {
  let s = text;
  let negative = false;
  if (s.startsWith("-")) {
    negative = true;
    s = s.slice(1);
  }
  const point = s.indexOf(".");
  let whole = s;
  let fraction = "";
  if (point >= 0) {
    if (integer) return null;
    whole = s.slice(0, point);
    fraction = s.slice(point + 1);
    if (!isDigits(fraction)) return null;
    if (whole !== "" && !isDigits(whole)) return null;
  } else if (!isDigits(whole)) {
    return null;
  }
  whole = whole.replace(/^0+/, "");
  fraction = fraction.replace(/0+$/, "");
  if (whole === "" && fraction === "") negative = false; // -0 is 0
  return { negative, whole, fraction };
}

function compareMagnitude(a: Decimal, b: Decimal): number {
  if (a.whole.length !== b.whole.length) return a.whole.length < b.whole.length ? -1 : 1;
  if (a.whole !== b.whole) return a.whole < b.whole ? -1 : 1;
  const width = Math.max(a.fraction.length, b.fraction.length);
  const fa = a.fraction.padEnd(width, "0");
  const fb = b.fraction.padEnd(width, "0");
  if (fa !== fb) return fa < fb ? -1 : 1;
  return 0;
}

function compareDecimal(a: Decimal, b: Decimal): number {
  if (a.negative !== b.negative) return a.negative ? -1 : 1;
  const m = compareMagnitude(a, b);
  return a.negative ? -m : m;
}

function bound(name: string, text: string | null | undefined): Decimal | null {
  if (text == null) return null;
  const d = parseDecimal(text, false);
  if (d === null) throw new Error(`rules.${name} must be a decimal number, such as "0" or "-2.5" (got "${text}")`);
  return d;
}

function fail(code: string, message: string): InputCheck {
  return { valid: false, value: null, code, message };
}

/**
 * One input checked as a GOV.UK form checks it: empty first, then length,
 * then the format its kind needs, then the pattern, then the range, each
 * failure with the message to show. The rules are the caller's, so a bad one
 * throws whatever was typed.
 */
export function validateInput(value: string, rules: InputRules): InputCheck {
  const label = trim(rules.label);
  if (label === "") throw new Error("an input needs a label, such as \"Full name\", to write its error messages");
  const numeric = rules.kind === "number" || rules.kind === "integer";
  if (rules.kind !== "text" && rules.kind !== "email" && !numeric) throw new Error(`unknown input kind "${rules.kind}"`);
  const { minLength, maxLength } = rules;
  if (minLength != null && minLength < 0) throw new Error("rules.minLength must not be negative");
  if (maxLength != null && maxLength < 0) throw new Error("rules.maxLength must not be negative");
  if (minLength != null && maxLength != null && minLength > maxLength) {
    throw new Error("rules.minLength must not be more than rules.maxLength");
  }
  if (!numeric && rules.min != null) throw new Error("rules.min only applies to number and integer inputs");
  if (!numeric && rules.max != null) throw new Error("rules.max only applies to number and integer inputs");
  const min = bound("min", rules.min);
  const max = bound("max", rules.max);
  if (min !== null && max !== null && compareDecimal(min, max) > 0) {
    throw new Error("rules.min must not be more than rules.max");
  }
  // A bad pattern fails here, on every call, not only when someone types.
  if (rules.pattern != null) matchesPattern(rules.pattern, "");

  const text = trim(value);
  if (text === "") {
    return rules.required ? fail("required", `Enter ${lowerFirst(label)}`) : { valid: true, value: "", code: null, message: null };
  }
  const length = Array.from(text).length;
  if (maxLength != null && length > maxLength) return fail("too-long", `${label} must be ${maxLength} characters or less`);
  if (minLength != null && length < minLength) return fail("too-short", `${label} must be ${minLength} characters or more`);

  let number: Decimal | null = null;
  if (rules.kind === "email" && !isEmail(text)) {
    return fail("email", "Enter an email address in the correct format, like name@example.com");
  }
  if (rules.kind === "number") {
    number = parseDecimal(text, false);
    if (number === null) return fail("number", `${label} must be a number`);
  }
  if (rules.kind === "integer") {
    number = parseDecimal(text, true);
    if (number === null) return fail("integer", `${label} must be a whole number`);
  }

  if (rules.pattern != null && !matchesPattern(rules.pattern, text)) {
    return fail("pattern", rules.patternMessage ?? `Enter ${lowerFirst(label)} in the correct format`);
  }

  if (number !== null) {
    const low = min !== null && compareDecimal(number, min) < 0;
    const high = max !== null && compareDecimal(number, max) > 0;
    if (low || high) {
      const code = low ? "too-small" : "too-large";
      if (min !== null && max !== null) return fail(code, `${label} must be between ${rules.min} and ${rules.max}`);
      if (low) return fail(code, `${label} must be ${rules.min} or more`);
      return fail(code, `${label} must be ${rules.max} or less`);
    }
  }
  return { valid: true, value: text, code: null, message: null };
}