Defensive Design
Input sanitisation means cleaning data before the program uses it. It removes or replaces characters that are not expected or allowed, so only acceptable characters reach the part of the program that stores, displays or processes the value.
You sanitise input to anticipate misuse. Someone might type a symbol by accident, or send unusual characters deliberately to see whether the program behaves differently. Filtering those characters out first reduces the chance of a crash, messy data or unexpected behaviour.
Sanitisation changes or filters the data; it does not simply check it and reject it. For example, a game profile name might allow letters and digits only. If you type Alex-R9!, sanitisation could keep AlexR9 and drop the hyphen and exclamation mark. The cleaned name is then used. This is different from validation, which tests whether data is sensible and rejects it if it is not. A program can sanitise input and validate it.
profile = input("Enter a profile name: ")
allowed = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
clean = ""
for character in profile:
if character in allowed:
clean = clean + character
print(clean)Output when the user types Alex-R9!:
Enter a profile name: Alex-R9!
AlexR9
The program builds a new string containing only letters and digits. Any other character is skipped, so the cleaned value is what gets printed and used later.
OCR GCSE Computer Science · Defensive Design