Robust Software
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.
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.
Validation compares the input with criteria — the specific rules the data must meet.
| Criterion | What it checks | Example |
|---|---|---|
| Type | that the data is the right kind: whole number, decimal or text | a ticket quantity must be a whole number |
| Range | that a number sits between a lowest and highest allowed value | a quiz answer must be from 1 to 4 |
| Length | that there are not too few or too many characters | a PIN must be exactly 4 digits |
| Format | that the characters follow a set pattern | a school email must end with the school's domain |
| Presence | that something has been entered at all | a 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.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.
Edexcel GCSE Computer Science · Input Validation