Skip to Content
Course content

44: Practice Exercise: Building Robust Input Validation

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I've seen this a thousand times in code reviews for junior devs: a programmer uses int.Parse() or Convert.ToInt32() and assumes that because the variable should be a number, the code will just work. They think they've "handled" the input because they've converted the string to an integer.

Assuming Parse() is Safe

Here is the classic mistake. Imagine you're building a simple system to take a quantity for a customer's order:

Console.WriteLine("How many widgets would you like to buy?");
int quantity = int.Parse(Console.ReadLine()); 
Console.WriteLine($"You ordered {quantity} widgets!");

On paper, this is fine. But the second a user accidentally hits the 's' key instead of '5', or leaves the field blank and hits Enter, your entire application crashes with a FormatException. In a real production environment, crashing the app because of a typo is an absolute non-starter. You can't trust your users; they will provide the weirdest, most unexpected input you can possibly imagine.

Embracing TryParse() and Validation Loops

The correct way to handle this isn't to wrap everything in a giant try-catch block—that's expensive and messy. Instead, we use int.TryParse(). This method doesn't throw an exception; it returns a boolean telling you if the conversion worked, and it uses an out parameter to give you the resulting value.

But just calling TryParse once isn't enough. If the input is bad, you don't want the program to just move on with a default value of 0; you want to give the user a chance to fix it. I always use a while loop for this pattern:

int quantity;
bool isValid = false;

while (!isValid)
{
    Console.WriteLine("Please enter the number of widgets (1-100):");
    string input = Console.ReadLine();

    if (int.TryParse(input, out quantity))
    {
        isValid = true;
    }
    else
    {
        Console.WriteLine("That wasn't a valid number. Please try again.");
    }
}

Now, the program is "robust." It won't crash, and it refuses to proceed until it has a usable piece of data.

Beyond the Type Check: Range and Logic

Here is the second trap: thinking that "it's an integer" means "it's a valid value." If I'm ordering widgets, I can't order -500 of them. If I'm entering my age, I can't be 12,000 years old.

Validation isn't just about data types; it's about business logic. I recommend combining your type check and your range check into a single validation step. This keeps your loop clean and ensures the data is actually useful for the rest of your program.

int quantity;
bool isValid = false;

while (!isValid)
{
    Console.Write("Enter quantity (1-100): ");
    if (int.TryParse(Console.ReadLine(), out quantity) && quantity >= 1 && quantity <= 100)
    {
        isValid = true;
    }
    else
    {
        Console.WriteLine("Invalid entry. Please enter a whole number between 1 and 100.");
    }
}

By chaining the TryParse with the range comparison using the && operator, we ensure that isValid only becomes true when the input is both a valid integer AND within our acceptable bounds. This is the foundation of professional-grade input handling.




📋 Practical Task

Exercise: The Warehouse Inventory Intake System

You are writing a console tool for a warehouse manager to log new shipments. The manager needs to enter three specific pieces of data, and the program must not proceed to the final summary until all three are validated correctly.

  • Item ID: Must be a positive integer greater than 0.
  • Quantity: Must be a positive integer between 1 and 10,000.
  • Weight (kg): Must be a valid decimal/double between 0.1 and 500.0.

Requirements:

  • Implement a while loop for each input to ensure the user is prompted repeatedly until they provide valid data.
  • Use TryParse (either int.TryParse or double.TryParse) to prevent the application from crashing on non-numeric input.
  • Provide a specific error message if the input is either the wrong type or outside the allowed range.
  • Once all three are collected, print a final confirmation message: "Shipment Logged: Item #[ID], Quantity: [Qty], Weight: [Weight]kg".
Rating
0 0

There are no comments for now.

to be the first to leave a comment.