Functional Weave
Code in Python

form.iso-date@1.0.0

impl/python.py

1,795 bytes · the Python 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.

from .form_date_parts import DateParts, DateRules, validate_date_parts  ← from form.date-parts ^1.0.0 · built alongside by fune
from .form_iso_date_types import IsoDateCheck

# ASCII whitespace only, so all three languages trim the same characters.
_SPACE = " \t\n\r\f\v"


def _iso_shape(value: str) -> bool:
    # YYYY-MM-DD with ASCII digits: what <input type="date"> submits, and
    # nothing else (no time, no offset, no other script's digits).
    if len(value) != 10:
        return False
    for i, ch in enumerate(value):
        if i in (4, 7):
            if ch != "-":
                return False
        elif not ("0" <= ch <= "9"):
            return False
    return True


def validate_iso_date(value: str, label: str, required: bool, rules: DateRules) -> IsoDateCheck:
    """A date picker's value, checked with form.date-parts' rules and
    messages. Pure calendar arithmetic on the string: no datetime, so no time
    zone can move the day; "today" is passed in by the caller."""
    # Called with empty boxes first, so a bad label or bad rules raise
    # whatever was typed, and its answer is the "Enter ..." message.
    empty = validate_date_parts(DateParts(day="", month="", year=""), label, rules)
    typed = value.strip(_SPACE)
    if typed == "":
        if required:
            return IsoDateCheck(valid=False, date=None, message=empty.message)
        return IsoDateCheck(valid=True, date=None, message=None)
    if not _iso_shape(typed):
        return IsoDateCheck(valid=False, date=None, message="%s must be a real date" % label.strip(_SPACE))
    check = validate_date_parts(DateParts(day=typed[8:10], month=typed[5:7], year=typed[0:4]), label, rules)
    if check.valid:
        return IsoDateCheck(valid=True, date=check.date, message=None)
    return IsoDateCheck(valid=False, date=None, message=check.message)