Data validation routines
What is Data Validation?
Validation is an automatic check performed by a program to ensure that data entered by a user is sensible, reasonable, and within acceptable limits before it is processed or stored. Validation does not guarantee that data is correct - it only checks that it is plausible. For example, a program can check that an age falls within a realistic range, but it cannot know whether the number entered is the user's actual age.
Validation routines are a core part of writing robust programs - programs that continue to work correctly even when users supply unexpected or incorrect input. Without validation, a program may crash, produce wrong results, or store nonsensical data.
Three Common Validation Checks
AQA requires you to be able to write three types of validation routine. Each tab below shows the check, a real-world context where it applies, and working code in all three languages.
Empty String Check
An empty string check verifies that the user has actually typed something rather than just pressing Enter. It is one of the simplest and most commonly needed validations. Real-world uses include: a required name field in a registration form, a search box that must not be submitted blank, or a username that must not be empty.
The check tests whether the length of the string is zero, or equivalently whether the string equals "". If the input is empty, the user is prompted to try again using a loop.
# Python -- empty string check
# Keeps asking until the user types something
def getUsername():
username = input("Enter your username: ")
while username == "": # check: is the string empty?
print("Username cannot be blank. Please try again.")
username = input("Enter your username: ")
return username # only returns a non-empty string
name = getUsername()
print("Welcome, " + name)
' VB.NET -- empty string check
' Keeps asking until the user types something
Function getUsername() As String
Dim username As String
Console.Write("Enter your username: ")
username = Console.ReadLine()
Do While username = "" ' check: is the string empty?
Console.WriteLine("Username cannot be blank. Please try again.")
Console.Write("Enter your username: ")
username = Console.ReadLine()
Loop
Return username ' only returns a non-empty string
End Function
Dim name As String = getUsername()
Console.WriteLine("Welcome, " & name)
// C# -- empty string check
// Keeps asking until the user types something
static string GetUsername()
{
Console.Write("Enter your username: ");
string username = Console.ReadLine();
while (username == "") // check: is the string empty?
{
Console.WriteLine("Username cannot be blank. Please try again.");
Console.Write("Enter your username: ");
username = Console.ReadLine();
}
return username; // only returns a non-empty string
}
string name = GetUsername();
Console.WriteLine("Welcome, " + name);
Minimum Length Check
A minimum length check verifies that the user's input contains at least a certain number of characters. This is commonly used for passwords (e.g. at least 8 characters), product codes (e.g. at least 6 characters), or any field where very short entries are invalid.
The check compares the length of the string against the required minimum. If the length is less than that minimum, the input is rejected and the user is prompted to try again.
# Python -- minimum length check
# Password must be at least 8 characters
def getPassword():
password = input("Enter a password (min 8 characters): ")
while len(password) < 8: # check: is it long enough?
print("Password too short. Must be at least 8 characters.")
password = input("Enter a password (min 8 characters): ")
return password
pw = getPassword()
print("Password accepted.")
' VB.NET -- minimum length check
' Password must be at least 8 characters
Function getPassword() As String
Dim password As String
Console.Write("Enter a password (min 8 characters): ")
password = Console.ReadLine()
Do While password.Length < 8 ' check: is it long enough?
Console.WriteLine("Password too short. Must be at least 8 characters.")
Console.Write("Enter a password (min 8 characters): ")
password = Console.ReadLine()
Loop
Return password
End Function
Dim pw As String = getPassword()
Console.WriteLine("Password accepted.")
// C# -- minimum length check
// Password must be at least 8 characters
static string GetPassword()
{
Console.Write("Enter a password (min 8 characters): ");
string password = Console.ReadLine();
while (password.Length < 8) // check: is it long enough?
{
Console.WriteLine("Password too short. Must be at least 8 characters.");
Console.Write("Enter a password (min 8 characters): ");
password = Console.ReadLine();
}
return password;
}
string pw = GetPassword();
Console.WriteLine("Password accepted.");
Range Check
A range check verifies that a numeric value falls within a defined lower and upper boundary. Real-world uses include: a score between 0 and 100, a month number between 1 and 12, a star rating between 1 and 5, or an age between 0 and 120. Any value outside the permitted range is rejected.
The condition uses OR: the value is invalid if it is below the lower bound or above the upper bound. Both bounds are usually included (inclusive range).
# Python -- range check
# Score must be between 0 and 100 (inclusive)
def getScore():
score = int(input("Enter a score (0-100): "))
while score < 0 or score > 100: # check: is it within range?
print("Invalid score. Must be between 0 and 100.")
score = int(input("Enter a score (0-100): "))
return score
result = getScore()
print("Score recorded: " + str(result))
' VB.NET -- range check
' Score must be between 0 and 100 (inclusive)
Function getScore() As Integer
Dim score As Integer
Console.Write("Enter a score (0-100): ")
score = CInt(Console.ReadLine())
Do While score < 0 Or score > 100 ' check: is it within range?
Console.WriteLine("Invalid score. Must be between 0 and 100.")
Console.Write("Enter a score (0-100): ")
score = CInt(Console.ReadLine())
Loop
Return score
End Function
Dim result As Integer = getScore()
Console.WriteLine("Score recorded: " & result)
// C# -- range check
// Score must be between 0 and 100 (inclusive)
static int GetScore()
{
Console.Write("Enter a score (0-100): ");
int score = int.Parse(Console.ReadLine());
while (score < 0 || score > 100) // check: is it within range?
{
Console.WriteLine("Invalid score. Must be between 0 and 100.");
Console.Write("Enter a score (0-100): ");
score = int.Parse(Console.ReadLine());
}
return score;
}
int result = GetScore();
Console.WriteLine("Score recorded: " + result);
Key Takeaways
- Validation checks that data is sensible and within acceptable limits - it does not confirm whether the data is actually correct, only that it is plausible.
- An empty string check rejects input where the user has entered nothing at all (string length equals zero).
- A minimum length check rejects input shorter than a required number of characters (e.g. a password fewer than 8 characters long).
- A range check rejects numeric input outside a defined lower and upper boundary, using an OR condition to catch both extremes.
- Validation routines use a while loop to keep re-prompting the user until valid data is entered, not a single IF statement that would allow the program to continue with invalid data.
- Multiple validation checks can be combined using logical operators to enforce several rules at once in a single routine.