from typing import Optional, Tuple from .form_validate_input_types import InputCheck, InputRules from .text_pattern_match import matches_pattern from .validation_email import is_email # ASCII whitespace only, so all three languages trim the same characters # (str.strip() with no argument would also take Unicode spaces). _SPACE = " \t\n\r\f\v" # A decimal is (negative, whole digits without leading zeros, fraction digits # without trailing zeros); zero is (False, "", ""). Decimal = Tuple[bool, str, str] def _lower_first(label: str) -> str: # "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. def upper(i: int) -> bool: return i < len(label) and "A" <= label[i] <= "Z" if upper(0) and not upper(1): return chr(ord(label[0]) + 32) + label[1:] return label def _is_digits(s: str) -> bool: # ASCII digits only: str.isdigit() accepts "٣". return s != "" and all("0" <= ch <= "9" for ch in s) def _parse_decimal(text: str, integer: bool) -> Optional[Decimal]: # -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. s = text negative = False if s.startswith("-"): negative = True s = s[1:] point = s.find(".") whole = s fraction = "" if point >= 0: if integer: return None whole = s[:point] fraction = s[point + 1:] if not _is_digits(fraction): return None if whole != "" and not _is_digits(whole): return None elif not _is_digits(whole): return None whole = whole.lstrip("0") fraction = fraction.rstrip("0") if whole == "" and fraction == "": negative = False # -0 is 0 return (negative, whole, fraction) def _compare_magnitude(a: Decimal, b: Decimal) -> int: if len(a[1]) != len(b[1]): return -1 if len(a[1]) < len(b[1]) else 1 if a[1] != b[1]: return -1 if a[1] < b[1] else 1 width = max(len(a[2]), len(b[2])) fa = a[2].ljust(width, "0") fb = b[2].ljust(width, "0") if fa != fb: return -1 if fa < fb else 1 return 0 def _compare_decimal(a: Decimal, b: Decimal) -> int: if a[0] != b[0]: return -1 if a[0] else 1 m = _compare_magnitude(a, b) return -m if a[0] else m def _bound(name: str, text: Optional[str]) -> Optional[Decimal]: if text is None: return None d = _parse_decimal(text, False) if d is None: raise ValueError('rules.%s must be a decimal number, such as "0" or "-2.5" (got "%s")' % (name, text)) return d def _fail(code: str, message: str) -> InputCheck: return InputCheck(valid=False, value=None, code=code, message=message) def validate_input(value: str, rules: InputRules) -> InputCheck: """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 raises whatever was typed.""" label = rules.label.strip(_SPACE) if label == "": raise ValueError('an input needs a label, such as "Full name", to write its error messages') kind = rules.kind numeric = kind in ("number", "integer") if kind not in ("text", "email") and not numeric: raise ValueError('unknown input kind "%s"' % kind) min_length, max_length = rules.min_length, rules.max_length if min_length is not None and min_length < 0: raise ValueError("rules.minLength must not be negative") if max_length is not None and max_length < 0: raise ValueError("rules.maxLength must not be negative") if min_length is not None and max_length is not None and min_length > max_length: raise ValueError("rules.minLength must not be more than rules.maxLength") if not numeric and rules.min is not None: raise ValueError("rules.min only applies to number and integer inputs") if not numeric and rules.max is not None: raise ValueError("rules.max only applies to number and integer inputs") low_bound = _bound("min", rules.min) high_bound = _bound("max", rules.max) if low_bound is not None and high_bound is not None and _compare_decimal(low_bound, high_bound) > 0: raise ValueError("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 is not None: matches_pattern(rules.pattern, "") text = value.strip(_SPACE) if text == "": if rules.required: return _fail("required", "Enter %s" % _lower_first(label)) return InputCheck(valid=True, value="", code=None, message=None) length = len(text) # code points, as in the other two languages if max_length is not None and length > max_length: return _fail("too-long", "%s must be %d characters or less" % (label, max_length)) if min_length is not None and length < min_length: return _fail("too-short", "%s must be %d characters or more" % (label, min_length)) number: Optional[Decimal] = None if kind == "email" and not is_email(text): return _fail("email", "Enter an email address in the correct format, like name@example.com") if kind == "number": number = _parse_decimal(text, False) if number is None: return _fail("number", "%s must be a number" % label) if kind == "integer": number = _parse_decimal(text, True) if number is None: return _fail("integer", "%s must be a whole number" % label) if rules.pattern is not None and not matches_pattern(rules.pattern, text): message = rules.pattern_message if message is None: message = "Enter %s in the correct format" % _lower_first(label) return _fail("pattern", message) if number is not None: low = low_bound is not None and _compare_decimal(number, low_bound) < 0 high = high_bound is not None and _compare_decimal(number, high_bound) > 0 if low or high: code = "too-small" if low else "too-large" if low_bound is not None and high_bound is not None: return _fail(code, "%s must be between %s and %s" % (label, rules.min, rules.max)) if low: return _fail(code, "%s must be %s or more" % (label, rules.min)) return _fail(code, "%s must be %s or less" % (label, rules.max)) return InputCheck(valid=True, value=text, code=None, message=None)