Validation & verification
Handout
This page needs a recent browser (with SharedArrayBuffer support). Please update Chrome, Edge, Firefox or Safari to the latest version.
Why validate input
- Validation checks that input is sensible before the program uses it.
- "Garbage in, garbage out" — bad data leads to wrong answers.
- The program decides to accept or reject the value.
Explore
The validation steps
Read the input, check it, then accept or reject — bad data never gets used.
Range check
- A range check makes sure a number is between a low and a high limit.
- Example: a month must be from 1 to 12.
month = 13
if 1 <= month <= 12:
print("Accepted")
else:
print("Rejected")
Length check
- A length check makes sure text is not too short or too long.
len(text)gives the number of characters.
password = "abc"
if len(password) >= 8:
print("Accepted")
else:
print("Too short")
Presence check
- A presence check makes sure something was actually entered.
- An empty string
""means the user typed nothing.
Verification: checking the copy
- Verification checks that data was copied or typed correctly.
- A double-entry check asks for the value twice and compares them.
- A visual check means a human reads it back on screen.
In the exam: types of check
- Know these validation checks: range, length, type, presence, format, check digit.
IF Age >= 0 AND Age <= 120 THEN
OUTPUT "Valid"
ELSE
OUTPUT "Invalid"
ENDIF
Common mistakes
- Validation checks data is sensible (range, length, type); verification checks it was entered correctly.
- A range check needs both a lower and an upper limit.
Now you try
- Each function returns
Trueto accept orFalseto reject. - Press Check answer to test your code.
Write valid_age(a) that returns True when a is a sensible age (0 to 120 inclusive), otherwise False. This is a range check.
Click Run to see the output here.
Write valid_password(p) that returns True when the password is at least 8 characters long. This is a length check.
Click Run to see the output here.
Write is_present(s) that returns True when something was entered, and False for an empty string "". This is a presence check.
Click Run to see the output here.