CSCI 1301

Input Validation

1. Learning Objectives

  • Why input validation is needed?
  • What is C# TryParse method?
  • How to perform input validation in programs?

2. What is Input Validation?

real-world programs deal with various types of input: either from human user, by requesting data from a server, reading a file, etc. Whenever a program receives information from an external source there is a possibility that input is somehow invalid.

Specifically when asking for input from user:

  • user may misunderstand the instructions and consequently provide invalid input
  • user may not read instructions at all and just press button/enter key to continue
  • user may intentionally provide bad input to try find exploitable vulnerabilities in the program

Instead of program proceeding with the bad input or crashing when user provides bad input, the program should detect invalid input and inform the user to correct the mistake in order to proceed.

Programs can achieve this behavior by performing input validation after receiving input from user. During this step the program checks that user input is within valid range. The program will proceed if input is valid and display error otherwise.

3. Why Not Use Parse

Recall we have seen a Parse method before that enables converting a string value to numeric data type. The syntax for that command is

1Console.Write("Enter number: ");
2string numericString = Console.ReadLine();
4// convert input to int type
5int a = int.Parse(numericString);
7// convert input to float type
8float b = float.Parse(numericString);
10// convert input to double type
11double c = double.Parse(numericString);
13// convert input to decimal type
14decimal d = decimal.Parse(numericString);

You might also remember that this Parse method will fail in several situations:

  • when input is not numeric at all, e.g. "abc"
  • when input contains punctuation or symbols, e.g. "$ 5"
  • fractional values cannot be parsed as integers, e.g "5.4" will throw an error when using int.Parse

When the Parse method fails, the program crashes. This is not desired behavior. Ideally the program should detect invalid input and prompt user to enter a new, valid value.

This method was introduced earlier because the syntax is easy to understand. It is useful in situations where it is safe to assume the input can be parsed, for example when input is received from another program.

4. Input Validation with TryParse

To handle input from human user, we can use a different method: TryParse. The syntax looks like this:

1int number;
2bool result = int.TryParse(stringValue, out number);

There are a few things to pay attention to in the above syntax:

  • bool result tells you if the parsing succeeded:

    • it will be true if the string value was successfully converted to a number
    • it will be false when parsing fails
  • value of number will be the converted numeric value if parse operation succeeds; when parsing fails value of number will always be 0.

TryParse syntax is similar for other data types:

1Console.Write("Enter number: ");
2string numericString = Console.ReadLine();
4// TryParse to int type
5// Notice: this single-line syntax is also valid
6bool intResult = int.TryParse(numericString, out int intValue);
8// TryParse to float type
9bool floatResult = float.TryParse(numericString, out float floatValue);
11// TryParse to double type
12bool doubleResult = double.TryParse(numericString, out double doubleValue);
14// TryParse to decimal type
15bool decimalResult = decimal.TryParse(numericString, out decimal decimalValue);

While not demonstrated in the example above, you can also use long.TryParse, char.TryParse and bool.TryParse methods.

TryParse Example

Experiment with the following code by entering different inputs and observe how the value of number and result variables change when you enter:

  • whole numbers, e.g. 3845
  • fractional input, e.g. 5.67
  • text input, e.g abc

Does the program crash?

TryParse allows converting inputs to non-string types without crashing the program. It is a preferable option over Parse when requesting input from user.

5. Ensuring Valid Input

We can now write programs to handle user input without crashing. We still need to achieve the behavior of re-requesting input when it is invalid. Here is a simple algorithm of how to accomplish this behavior:

  1. prompt for user input

  2. check if input is valid

  3. a) when it is valid proceed to the next command

    b) when it is NOT valid (ideally) explain what is wrong with input, then request new input

This algorithm helps to identify some of the statements we need to implement this behavior. We will need: 1) a looping statement to repeatedly request for input 2) if-statement to choose between 3 a and b

1int number;
3// loop that will repeat until
4// we have valid answer
7 // 1. get input from user
8 Console.Write("Enter positive number: ");
9 string input = Console.ReadLine();
11 // try to parse the input
12 bool success = int.TryParse(input, out number);
14 // 2. check if input is valid
15 if(success && number >= 0){
16 // 3. a) terminate loop on valid input
17 break;
18 }
20 // 3 b)
21 // explain the error
22 Console.WriteLine("That's not a positive integer!");
23 // code will repeat because it is within a loop
25} while(true);
27Console.WriteLine($"You entered {number}!");

This implementation uses a do-while loop because we must request user input at least once. It is also perfectly fine to implement this code using a while loop.

Here is another example demonstrating user validation. This example uses string data type, so TryParse is not needed (why?). This method uses a while loop.

6. Summary

Why input validation is needed?

You cannot trust user to provide valid input. User may be careless or purposely try to break the program by providing invalid input. Input validation enables to prevent issues caused by invalid input.

What is C# TryParse method?

TryParse method enables parsing string values to numeric, bool and char data types. It does not crash if the conversion fails. It returns two pieces of data: one to indicate if conversion succeeded and one that holds the converted value.

How to perform input validation in programs?

A general strategy is to use a looping statement, ask for input, check if input is valid and terminate looping if valid input was received.