DEV Community

Fiaz Miah
Fiaz Miah

Posted on Edited on

Validate an ASCII count before converting it to an integer

An integer parser and an input validator answer different questions. int(text) can produce a number from input that a small protocol may want to reject: whitespace, a leading plus sign, or leading zeros.

Consider a hypothetical count field with a deliberately narrow contract:

  • The input must be a string containing ASCII digits.
  • Values range from 0 through 9999.
  • Zero is written as 0; other values have no leading zeros.
  • Spaces, signs and line breaks are invalid.

These are choices for this example, not rules every application should adopt. A localized form may reasonably accept other digit scripts. An identifier may need to preserve leading zeros. Decide the contract before choosing a parser.

Validate the representation first

import re

def parse_count(text):
    # A deliberately narrow wire format, not a general number parser.
    if not isinstance(text, str) or re.fullmatch(r'0|[1-9][0-9]{0,3}', text) is None:
        raise ValueError('expected an ASCII integer from 0 to 9999 without leading zeros')
    return int(text)
Enter fullscreen mode Exit fullscreen mode

There are two valid forms: exactly 0, or a nonzero ASCII digit followed by at most three more ASCII digits. The result is converted to an integer only after the complete string has passed validation.

fullmatch matters here. Accepting a matching prefix would leave room for extra characters after the number. Writing the character range explicitly also makes the ASCII restriction visible in the code. The Python regular-expression documentation describes whole-string matching and character classes.

The type check is part of the contract. This function accepts text, not a mixture of integers, booleans and strings that happen to describe similar values. It raises ValueError for every rejected input in this example, including the wrong type; another interface might distinguish a type error from an invalid string.

Test what must stay invalid

Happy-path tests alone would miss most of the reason for this function. These checks include both boundaries and representations that conversion might otherwise normalize:

for text, expected in [('0', 0), ('7', 7), ('9999', 9999)]:
    assert parse_count(text) == expected

for text in ['00', '+7', '7\n', ' 7', '7.0', '10000', '٧', '', None]:
    try:
        parse_count(text)
    except ValueError:
        pass
    else:
        raise AssertionError(repr(text))

print('12 synthetic cases passed')
Enter fullscreen mode Exit fullscreen mode

The single digit ٧ is an Arabic-Indic seven. Its rejection is intentional for this ASCII-only example, not a claim that it is an invalid way to write a number generally.

The accompanying script was run locally and all 12 synthetic cases passed. That result checks this small example; it does not establish production reliability or exhaust every possible input. Python assertions should be run without optimization for these checks.

Decide whether normalization belongs at this boundary

Calling .strip() before validation would change the contract: 7 would become accepted input. That can be helpful in a human-facing form, but it should be a deliberate decision. A strict interchange format may need to reject the same text so that different implementations agree on what was sent.

The upper bound is also specific to the field. A valid count of 9999 says nothing about whether the caller is permitted to request that much work. Authorization and resource limits still belong in the surrounding application.

Keep the accepted representation, the numeric range and the operational limit as explicit decisions. A successful conversion answers only one of those questions.

Top comments (0)