Cybersecurity Input Validation
Accept a deliberately small input contract and reject the rest.
How it works
Validation checks that input matches the application’s expected type, length and meaning. It does not make a value safe for every output context. Define bounds before conversion and reject ambiguous values; silently fixing an unexpected value can hide a bug. The contract below accepts ASCII digits for a positive loan quantity with a small maximum.
Run the code
Save the complete source as input-validation.py in a separate learning folder, then run python input-validation.py. The reviewed runtime is Python 3.12.14 with the standard library; no third-party packages are required. These are local examples, not browser playground programs. Apache, MySQL and PHP are not needed.
Example
import re
def quantity(value):
if not isinstance(value, str) or not re.fullmatch(r"[0-9]{1,2}", value):
raise ValueError("quantity format")
number = int(value)
if not 1 <= number <= 12:
raise ValueError("quantity range")
return number
assert quantity("3") == 3
for bad in ["0", "13", "-1", "3.0", "", "12", None]:
try:
quantity(bad)
except ValueError:
continue
raise AssertionError(bad)
print("valid quantity accepted; seven invalid inputs rejected")
Expected result
valid quantity accepted; seven invalid inputs rejected
The regular expression constrains format before integer conversion, and the range check adds business meaning. The invalid cases cover empty text, signs, decimal notation, oversized quantity, non-ASCII digits and the wrong type. A different product may legitimately support other formats; change the contract and tests together.
Technical reference: OWASP Cheat Sheet Series. Check the guidance for your actual platform and deployment.