Menu

Robust Software

Input Validation

Input validation is the process of checking the data a user enters against a set of rules before the program accepts and uses it. Anything that fails the rules is rejected, so the rest of the program only ever works with sensible data.

Why validation makes software robust

Robust software keeps working correctly whatever it is given. If validation is inadequate, invalid, unexpected or harmful data gets into the system and is stored, passed on or used in calculations — that is a vulnerability. A score field that accepts 9000 ruins a leaderboard, an empty name breaks a printout, and a quote mark typed into a search box can change the instruction a database receives. Catching the problem as the data is entered is far cheaper than repairing bad records later.

Criteria to validate against

Validation compares the input with criteria — the specific rules the data must meet.

CriterionWhat it checksExample
Typethat the data is the right kind: whole number, decimal or texta ticket quantity must be a whole number
Rangethat a number sits between a lowest and highest allowed valuea quiz answer must be from 1 to 4
Lengththat there are not too few or too many charactersa PIN must be exactly 4 digits
Formatthat the characters follow a set patterna school email must end with the school's domain
Presencethat something has been entered at alla delivery address box is not left empty

A username is checked for presence, then length, then format. Only when all three checks pass is it accepted.

username = input("Choose a username: ")
if username == "":
    print("You must enter a username.")
elif len(username) < 3 or len(username) > 12:
    print("Use between 3 and 12 characters.")
elif not username.isalnum():
    print("Use letters and numbers only.")
else:
    print("Username accepted.")

Output when the user types jamie99:

Choose a username: jamie99
Username accepted.

Parsing input to spot security problems

Software can also be programmed to parse user input: to work through it piece by piece looking for suspicious characters or patterns. Angle brackets, semicolons and quote marks are harmless in ordinary writing but can change the meaning of a command or a database query, so a program may block them, or reject text far longer than expected, before the data is used.

display_name = input("Enter a display name: ")
blocked = ["<", ">", ";"]
found = False
for symbol in blocked:
    if display_name.find(symbol) != -1:
        found = True
if found:
    print("Display name rejected: it contains a blocked symbol.")
else:
    print("Display name saved.")

Output when the user types Riley;99:

Enter a display name: Riley;99
Display name rejected: it contains a blocked symbol.

Validation checks input against criteria before it is used; exception handling deals with unexpected events while the program runs.

Practise this