Week 5 - Validation
Learning Goals
- Understand why validating user input matters.
- Apply existence, type and range checking in C#.
- Use
TryParseto safely convert strings to numbers. - Write reusable validation methods.
Key Concepts
Why Validate?
Programs can crash or produce incorrect results when users enter unexpected input. Validation checks whether data is acceptable before the program uses it.
Three Types of Validation
| Type | What it checks | Example |
|---|---|---|
| Existence | Has the user entered anything? | Name cannot be blank |
| Type | Is the value the right data type? | Price must be numeric |
| Range | Is the value within limits? | Quantity must be 0-999 |
Existence Check
Console.Write("Enter product name: ");
string name = Console.ReadLine();
if (string.IsNullOrWhiteSpace(name))
{
Console.WriteLine("Error: Name cannot be blank.");
}
Type Check with TryParse
Console.Write("Enter quantity: ");
string input = Console.ReadLine();
int quantity;
if (int.TryParse(input, out quantity))
{
Console.WriteLine($"Quantity accepted: {quantity}");
}
else
{
Console.WriteLine("Error: Quantity must be a whole number.");
}
Range Check
if (quantity < 0 || quantity > 999)
{
Console.WriteLine("Error: Quantity must be between 0 and 999.");
}
Combining Checks in a Loop
int quantity = -1;
bool valid = false;
while (!valid)
{
Console.Write("Enter quantity (0-999): ");
string input = Console.ReadLine();
if (!int.TryParse(input, out quantity))
{
Console.WriteLine("Must be a whole number. Try again.");
}
else if (quantity < 0 || quantity > 999)
{
Console.WriteLine("Must be between 0 and 999. Try again.");
}
else
{
valid = true;
}
}
Your Task
Create a new Console App called Week5_Validation.
Write a program that asks the user to enter a new product for the shop:
- Product name: existence check, cannot be blank
- Price: type check as
double, plus range check greater than 0 - Quantity: type check as
int, plus range check between 0 and 999
Once all three values are valid, display a confirmation.
Put each validated input into its own method, for example:
static string GetValidName() { ... }
static double GetValidPrice() { ... }
static int GetValidQuantity() { ... }
Extension
- Add a check that the product name is no longer than 30 characters.
- If the user fails validation 3 times in a row on any field, display a message and exit the program.
Common Mistakes to Avoid
- using
Convert.ToInt32()instead ofTryParse - forgetting the
outkeyword inTryParse - validating once instead of looping until the input is valid