Get up to 80 % extra points for free! More info:

Lesson 7 - Sanitizing user input in VB.NET

In the previous exercise, Solved tasks for Visual Basic .NET lesson 6, we've practiced our knowledge from previous lessons.

Lesson highlights

Are you looking for a quick reference on sanitizing user input in VB.NET instead of a thorough-full lesson? Here it is:

Using the TryParse() method to handle invalid user inputs and a While loop to keep the user entering:

Console.WriteLine("Enter a number:")
Dim a As Double
While Not Double.TryParse(Console.ReadLine(), a)
    Console.WriteLine("Invalid entry, please try again:")
End While

Using ReadKey() instead of ReadLine() when interested in one character only and the Else branch of a Select Case to handle invalid inputs:

Console.WriteLine("Do you like VB.NET?:")
Console.WriteLine("1 - yes")
Console.WriteLine("2 - maybe")
Console.WriteLine("3 - no")
Dim choice As Char = Console.ReadKey().KeyChar
Console.WriteLine()
Select Case choice
    Case "1"
        Console.WriteLine("Me too!")
    Case "2"
        Console.WriteLine("Come on, it's a nice language!")
    Case "3"
        Console.WriteLine("Maybe you should study harder")
    Case Else
        Console.WriteLine("Invalid option!")
End Select
Console.ReadKey()

Would you like to learn more? A complete lesson on this topic follows.

In the previous lesson, Solved tasks for Visual Basic .NET lesson 6, we introduced loops. Today's tutorial is going to be a little more relaxing because we're going to finish our calculator in Visual Basic .NET. We won't need it anymore after this, and it would be nice to finish it. You might already know that it lacks user input sanitation, which is what we're going to do today.

Let's bring up our calculator code:

Dim goOn As String = "yes"
While goOn = "yes"
    Console.WriteLine("Enter the first number:")
    Dim a As Double = Console.ReadLine()
    Console.WriteLine("Enter the second number:")
    Dim b As Double = Console.ReadLine()
    Console.WriteLine("Choose one of the following operations:")
    Console.WriteLine("1 - addition")
    Console.WriteLine("2 - subtraction")
    Console.WriteLine("3 - multiplication")
    Console.WriteLine("4 - division")
    Dim choice As Integer = Console.ReadLine()
    Dim result As Double = 0
    Select Case choice
        Case 1
            result = a + b
        Case 2
            result = a - b
        Case 3
            result = a * b
        Case 4
            result = a / b
    End Select
    If choice > 0 And choice < 5 Then
        Console.WriteLine("Result: {0}", result)
    Else
        Console.WriteLine("Invalid choice")
    End If
    Console.WriteLine("Would you like to make another calculation? [yes/no]")
    goOn = Console.ReadLine()
End While
Console.WriteLine("Thank you for using our calculator. Press any key to end the program.")
Console.ReadKey()

I had mentioned earlier that we should always sanitize user inputs. Let me tell you the secret to making successful and popular applications. It's very simple: You treat your users like total fools :) The sillier you expect the user to be, the more successful your applications will be. If the user enters "yes " (yes + space) rather than simply "yes", or he/she enters "Yes" (with a capital "Y"), the program would terminate. Which technically might not be due to user's silliness, more so because the user mistyped it. They could, however, enter something totally ridiculous, like: "maybe".

Either way, that's not the biggest problem in our program. When the user doesn't enter a number, but some nonsense instead, the whole program crashes with an error. Let's fix these two problems.

To validate the input before parsing it, we can use the TryParse() method instead of Parse(). The method returns True/False depending on whether the parsing succeeded or not. If you're asking how we get the parsed value from the method, the answer is that it'll be stored in a variable which we pass as the second parameter. The value of that variable will be affected. Let's now look at the sanitized retrieving of the first number, the parsing of the second number will be obviously analogical, so we can just copy it. Ideally, we should have created a method for it, so we wouldn't write the same code twice, but now is not the time to deal with all of that. We'll learn how to declare methods in the object-oriented programming course.

Console.WriteLine("Enter the first number:")
Dim a As Double
While Not Double.TryParse(Console.ReadLine(), a)
    Console.WriteLine("Invalid entry, please try again:")
End While

There is nothing difficult about the code shown above. First, we ask the user to enter the number and we declare the variable a. Then we insert TryParse() in the condition of a While loop and negate this condition with the Not operator. So while the method returns False, the loop will keep going and asking the user to enter another value. The entered text from the console will be parsed into a variable and the method will return True. If parsing fails, it will return False.

Now, let's look at the operational selection and continuation parts. We read both inputs as strings even though it's not quite appropriate to do so. It makes sense to read the numbers as strings since they may be longer that one character, so they must be submitted by pressing Enter during the selection of operations (1-4). Nonetheless, it's enough to read just a single character and we don't need to submit it by pressing enter. We read a single character using the Console.ReadKey() method, which we've already covered. To get the result as Char (character), we need to use the KeyChar property.

Dim choice As Char = Console.ReadKey().KeyChar
Dim result As Double = 0
Dim validChoice As Boolean = True
Select Case choice
    Case "1"
        result = a + b
    Case "2"
        result = a - b
    Case "3"
        result = a * b
    Case "4"
        result = a / b
    Case Else
        validChoice = False
End Select
If validChoice Then
    Console.WriteLine("Result: {0}", result)
Else
    Console.WriteLine("Invalid choice")
End If

We store the entered character as a Char into the variable choice. Because the range of characters can't be easily tested with conditions as with integers with our current knowledge, but we'll check it in another way. We prepare a Boolean variable validChoice, which is set to True (which we assume to be correct). The Select Case remains the same, we only put numbers in quotes because they're characters now. We add the Case Else, which will set our validChoice variable to False in case that some unspecified value was entered. Then, there is nothing easier than to test that variable. Try it, the program is much more intuitive now.

Finally, we need to modify the continuing prompt. We'll enter the Y/N characters and we'll make the input case-insensitive and respond to invalid values. We'll use the Select Case again and change our variable, goOn, to the Boolean datatype. It is unnecessary to describe this code, all that's worth mentioning is the Console.ReadKey().KeyChar.ToString().ToLower() i.e. method chaining, which reads a character from the console and returns it as a lowercase String.

Since this is a bigger piece of code, we'll use comments. We write them with single quotation marks. It is information for the programmer which the compiler ignores.

Dim goOn As String = "yes"
While goOn = "yes"
    ' reading numbers
    Console.WriteLine("Enter the first number:")
    Dim a As Double
    While Not Double.TryParse(Console.ReadLine(), a)
        Console.WriteLine("Invalid entry, please try again:")
    End While
    Console.WriteLine("Enter the second number:")
    Dim b As Double
    While Not Double.TryParse(Console.ReadLine(), b)
        Console.WriteLine("Invalid entry, please try again:")
    End While
    ' operation choice and calculation
    Console.WriteLine("Choose one of the following operations:")
    Console.WriteLine("1 - addition")
    Console.WriteLine("2 - subtraction")
    Console.WriteLine("3 - multiplication")
    Console.WriteLine("4 - division")
    Dim choice As Char = Console.ReadKey().KeyChar
    Dim result As Double = 0
    Dim validChoice As Boolean = True
    Select Case choice
        Case "1"
            result = a + b
        Case "2"
            result = a - b
        Case "3"
            result = a * b
        Case "4"
            result = a / b
        Case Else
            validChoice = False
    End Select
    If validChoice Then
        Console.WriteLine("Result: {0}", result)
    Else
        Console.WriteLine("Invalid choice")
    End If
    Console.WriteLine("Would you like to make another calculation? [yes/no]")
    ' request to continue
    validChoice = false
    While Not validChoice
        Select Case Console.ReadKey().KeyChar.ToString().ToLower()
            Case "y"
                goOn = True
                validChoice = True
            Case "n"
                goOn = False
                validChoice = True
            Case Else
                Console.WriteLine("Invalid option, please enter y/n")
        End Select
    End While
End While
Console.WriteLine("Thank you for using our calculator. Press any key to end the program.")
Console.ReadKey()

Console application
Welcome to our calculator
Enter the first number:
number
Invalid entry, please try again:
13
Enter the second number:
22
Choose one of the following operations:
1 - addition
2 - subtraction
3 - multiplication
4 - division
3
Result: 286
Would you like to make another calculation? [yes/no]
h
Invalid choice, please enter y/n

Congratulations, you've just created your first foolproof program :) The code became a little more complicated, but it's worth it in the end. In the future, we may refactor it and split it up into separate methods. We'll say that our calculator is done for now (for this course, anyway). We could maybe add some more mathematical functions, but we'll get to that later in the course.

In the next lesson, Arrays in VB.NET, we'll dive into new constructs. Arrays and advanced work with strings await our arrival. Then, we'll finish the constructs in this course. We're approaching end :)


 

Previous article
Solved tasks for Visual Basic .NET lesson 6
All articles in this section
Visual Basic (VB.NET) Basic Constructs
Skip article
(not recommended)
Arrays in VB.NET
Article has been written for you by Michal Zurek
Avatar
User rating:
2 votes
Activities