6.4.3 Validation
Why Validate?
Validation is the process of checking that input data meets the required criteria before a program uses it. Validation cannot guarantee data is correct (a user who enters their neighbour's date of birth passes a date validation), but it prevents data that is clearly in the wrong format or range from entering the system and causing errors, corruption or security vulnerabilities.
Four types of validation check are required at GCSE: length check, presence check, range check and pattern check.
Length Check
A length check verifies that a string has an acceptable number of characters — not too short and not too long.
MIN_LENGTH = 8
MAX_LENGTH = 16
def validate_length(value, min_len, max_len):
"""Returns True if value length is within the allowed range."""
return min_len <= len(value) <= max_len
password = input("Enter password (8-16 characters): ")
while not validate_length(password, MIN_LENGTH, MAX_LENGTH):
print("Invalid: password must be 8 to 16 characters long.")
password = input("Enter password (8-16 characters): ")
print("Password accepted.")
const int MIN_LENGTH = 8, MAX_LENGTH = 16;
string password = Console.ReadLine();
while (password.Length < MIN_LENGTH || password.Length > MAX_LENGTH) {
Console.WriteLine("Invalid: 8-16 characters required.");
password = Console.ReadLine();
}
Console.WriteLine("Password accepted.");
Const MIN_LENGTH As Integer = 8
Const MAX_LENGTH As Integer = 16
Dim password As String = Console.ReadLine()
Do While password.Length < MIN_LENGTH OrElse password.Length > MAX_LENGTH
Console.WriteLine("Invalid: 8-16 characters required.")
password = Console.ReadLine()
Loop
Console.WriteLine("Password accepted.")
Presence Check
A presence check verifies that a field has not been left blank — it contains at least one non-whitespace character.
def validate_presence(value):
"""Returns True if value is not empty after stripping whitespace."""
return len(value.strip()) > 0
name = input("Enter your name: ")
while not validate_presence(name):
print("Invalid: name cannot be blank.")
name = input("Enter your name: ")
print("Hello,", name.strip())
.strip() before checking means a name of only spaces also fails the check — pure whitespace is treated as empty.
string name = Console.ReadLine();
while (string.IsNullOrWhiteSpace(name)) {
Console.WriteLine("Invalid: name cannot be blank.");
name = Console.ReadLine();
}
Console.WriteLine("Hello, " + name.Trim());
Dim name As String = Console.ReadLine()
Do While String.IsNullOrWhiteSpace(name)
Console.WriteLine("Invalid: name cannot be blank.")
name = Console.ReadLine()
Loop
Console.WriteLine("Hello, " & name.Trim())
Range Check
A range check verifies that a numeric value falls within an acceptable minimum and maximum.
MIN_AGE = 0
MAX_AGE = 120
def validate_range(value, min_val, max_val):
"""Returns True if value is within the inclusive range."""
return min_val <= value <= max_val
age = int(input("Enter age: "))
while not validate_range(age, MIN_AGE, MAX_AGE):
print("Invalid: age must be between", MIN_AGE, "and", MAX_AGE)
age = int(input("Enter age: "))
print("Age accepted:", age)
const int MIN_AGE = 0, MAX_AGE = 120;
int age = int.Parse(Console.ReadLine());
while (age < MIN_AGE || age > MAX_AGE) {
Console.WriteLine("Invalid: age must be 0-120.");
age = int.Parse(Console.ReadLine());
}
Console.WriteLine("Age accepted: " + age);
Const MIN_AGE As Integer = 0
Const MAX_AGE As Integer = 120
Dim age As Integer = Integer.Parse(Console.ReadLine())
Do While age < MIN_AGE OrElse age > MAX_AGE
Console.WriteLine("Invalid: age must be 0-120.")
age = Integer.Parse(Console.ReadLine())
Loop
Console.WriteLine("Age accepted: " & age)
Pattern Check
A pattern check verifies that a string matches a required format or structure — for example, a postcode, a date, or a product code. At GCSE, pattern checks are typically implemented by checking specific characters or lengths without using regular expressions.
# Pattern check: product code must be exactly 6 characters,
# starting with 2 letters followed by 4 digits (e.g. AB1234)
def validate_product_code(code):
"""Returns True if code matches pattern: 2 letters + 4 digits."""
if len(code) != 6:
return False
if not code[0:2].isalpha(): # first two must be letters
return False
if not code[2:6].isdigit(): # last four must be digits
return False
return True
code = input("Enter product code (e.g. AB1234): ")
while not validate_product_code(code.upper()):
print("Invalid: must be 2 letters followed by 4 digits.")
code = input("Enter product code: ")
print("Code accepted:", code.upper())
bool ValidateProductCode(string code) {
code = code.ToUpper();
if (code.Length != 6) return false;
for (int i = 0; i < 2; i++)
if (!char.IsLetter(code[i])) return false;
for (int i = 2; i < 6; i++)
if (!char.IsDigit(code[i])) return false;
return true;
}
string code = Console.ReadLine();
while (!ValidateProductCode(code)) {
Console.WriteLine("Invalid: must be 2 letters + 4 digits.");
code = Console.ReadLine();
}
Console.WriteLine("Code accepted: " + code.ToUpper());
Function ValidateProductCode(code As String) As Boolean
code = code.ToUpper()
If code.Length <> 6 Then Return False
For i As Integer = 0 To 1
If Not Char.IsLetter(code(i)) Then Return False
Next
For i As Integer = 2 To 5
If Not Char.IsDigit(code(i)) Then Return False
Next
Return True
End Function
Dim code As String = Console.ReadLine()
Do While Not ValidateProductCode(code)
Console.WriteLine("Invalid: must be 2 letters + 4 digits.")
code = Console.ReadLine()
Loop
Console.WriteLine("Code accepted: " & code.ToUpper())
Key Takeaways
- Length check:
MIN <= len(value) <= MAX— reject too short or too long strings. - Presence check:
len(value.strip()) > 0— reject empty or whitespace-only input. - Range check:
MIN <= value <= MAX— reject numbers outside the valid range. - Pattern check: check specific character positions using
.isalpha(),.isdigit(), slicing — reject strings that do not match the required format. - Wrap all checks in a
while not valid:loop to keep asking until valid input is received.