DEV Community

Python Dev
Python Dev

Posted on

Stop Trusting User Input: How to Build a Python 'Validation Gate'

Stop Trusting User Input: How to Build a Python 'Validation Gate'

For Python beginners who want to stop bad data before it wrecks their scripts.

๐Ÿค” What Is a Validation Gate?

Think of a nightclub bouncer โ€” their only job is checking people at the door. A Validation Gate is the same: a block of code between input collection and program logic whose only job is to ask "is this data safe to enter?"

User Input โ†’ [VALIDATION GATE] โ†’ Business Logic โ†’ Output
โ†“
Bad input? STOP. Print error. Exit.

Bad data gets stopped immediately, instead of silently corrupting results 50 lines later.

๐Ÿ”ข Lower Bounds and Upper Bounds โ€” Both Matter

Most beginners only check one side:

if age < 0:
    print("Error: age can't be negative!")
    exit()
Enter fullscreen mode Exit fullscreen mode

That only protects one end of the range. What if someone types 99999? It's positive, so it passes โ€” but it's just as wrong.

Lower bound โ€” catches impossibly small values (e.g., Age = -5)
Upper bound โ€” catches unrealistically large values (e.g., Age = 99999)

Both are equally important.

๐Ÿš€ Why Upper Bounds Matter

User enters 9999 as their age. Your if age < 0 check passes. Now you calculate retirement_year = 2025 + (65 - 9999) and get -7909. No crash โ€” just a silent, absurd result. That's worse than a crash.

Upper-bound violations are caused by unit confusion, extra zeros, copy-paste errors, and malicious input. A proper gate catches all of them.

๐Ÿ› ๏ธ The Full Code

# validation_gate.py
# A beginner-friendly example of defensive input validation in Python


def get_validated_age(prompt="Enter your age: "):
    """
    Collects a user's age and validates it through 3 gates before
    allowing the value to proceed into the rest of the program.
    """

    # --- Define our realistic bounds ---
    MIN_AGE = 0    # An age below 0 is impossible
    MAX_AGE = 120  # An age above 120 is unrealistic for a human

    # --- Collect the raw input and clean up whitespace ---
    user_input = input(prompt).strip()

    # =============================================
    # GATE 1: Type Check
    # Is this actually a whole number?
    # We check this FIRST, before any math.
    # =============================================
    if not user_input.isdigit():
        print(f"โŒ Error: '{user_input}' is not a valid whole number.")
        print("   Please enter a number like 25 or 42.")
        exit()

    # Safe to convert to int now, since we already confirmed it's digits-only
    age = int(user_input)

    # =============================================
    # GATE 2: Lower Bound Check
    # Is the number above the minimum?
    # =============================================
    if age < MIN_AGE:
        print(f"โŒ Error: Age cannot be negative. You entered: {age}")
        exit()

    # =============================================
    # GATE 3: Upper Bound Check
    # Is the number below the maximum?
    # This is the gate most beginners forget!
    # =============================================
    if age > MAX_AGE:
        print(f"โŒ Error: {age} is not a realistic human age.")
        print(f"   Please enter a number between {MIN_AGE} and {MAX_AGE}.")
        exit()

    # =============================================
    # ALL GATES PASSED โœ…
    # Only reach here if the input is valid.
    # =============================================
    print(f"โœ… Valid age accepted: {age}")
    return age

# --- Main Program ---
if __name__ == "__main__":
    validated_age = get_validated_age()

    # Your actual program logic goes here, safe in the knowledge
    # that validated_age is a sensible number.
    print(f"\nProcessing your data with age = {validated_age}...")
    print("(Your real business logic would go here)")
Enter fullscreen mode Exit fullscreen mode

๐Ÿ” Key Points

.strip() โ€” Strips whitespace first. " 25 " becomes "25".

.isdigit() โ€” Checks every character is a digit. "25" passes. "abc" and "25.5" both fail. Always run this before any math to avoid a ValueError.

exit() โ€” Stops the program immediately. Use sys.exit(1) in larger projects.

Order matters. Type check first, then range. Checking if age < 0 before confirming age is a number crashes the moment someone types "abc".

๐Ÿงช 3 Edge Cases to Try

๐Ÿ”ด Scenario 1: Negative Number

Type: -5
Enter your age: -5
โŒ Error: '-5' is not a valid whole number.

Lesson: Gate 1 fires, not Gate 2. The - sign isn't a digit, so .isdigit() returns False immediately. Strict type-checking catches negatives as a free side effect.

๐ŸŸ  Scenario 2: Upper-Limit Violation

Type: 99999
Enter your age: 99999
โŒ Error: 99999 is not a realistic human age.
Please enter a number between 0 and 120.

Lesson: 99999 clears Gate 1 (it's digits) and Gate 2 (it's not negative) โ€” but Gate 3 catches it. This is the entire point of checking both bounds.

๐ŸŸก Scenario 3: Text and Decimals

Type: twenty five, then 25.5
Enter your age: twenty five
โŒ Error: 'twenty five' is not a valid whole number.

Lesson: Gate 1 rejects both before any numeric check runs. Type validation must come first.

โš ๏ธ Three Mistakes to Avoid

Mistake 1: Range before type. if age < 0 before .isdigit() crashes on text input. Type first, always.

Mistake 2: Only checking the lower bound. Positive โ‰  realistic. Define and check both MIN and MAX.

Mistake 3: Not exiting after a failed check.

# โŒ BAD โ€” program keeps running with bad data
if age < 0:
    print("Error: negative age")
Enter fullscreen mode Exit fullscreen mode

Always follow a failed check with exit(). Fail fast, fail loud, fail clearly.

โœ… The Golden Rules of Validation

A validation gate is cheap insurance against expensive bugs.

Type check first โ€” is this the right kind of data?
Lower bound second โ€” is it above the minimum?
Upper bound third โ€” is it below the maximum?

Positive doesn't mean realistic. Now go add a validation gate to your next script. ๐Ÿ

Positive doesn't mean realistic. Now go add a validation gate to your next script. ๐Ÿ

Mistake 2: Only checking the lower bound. Positive โ‰  realistic. Define and check both MIN and MAX.

Mistake 3: Not exiting after a failed check.

python# โŒ BAD โ€” program keeps running with bad data
if age < 0:
print("Error: negative age")

Always follow a failed check with exit(). Fail fast, fail loud, fail clearly.

โœ… The Golden Rules of Validation

A validation gate is cheap insurance against expensive bugs.

Type check first โ€” is this the right kind of data?
Lower bound second โ€” is it above the minimum?
Upper bound third โ€” is it below the maximum?

Positive doesn't mean realistic. Now go add a validation gate to your next script. ๐Ÿ

Top comments (1)

Collapse
 
pythondev2026 profile image
Python Dev

Yo guyz.....yeah ik the part after the snake emoji has repeated again but for some reason when i got in the editor to edit it out i cant seem to find it like it dissappears in edit section but is visible after publishing and during preview if anyone can help me then i would appreciate it a lot as this is my first post on any platform

Btw Thanks for reading i hope this was helpful!!!