Lesson 7 - Sanitizing user input in VB.NET

Visual Basic .NET Basics Sanitizing user input in VB.NET

In the previous lesson, Loops in VB.NET, 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.ReadKe­y().KeyChar.ToS­tring().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 "a"
                                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 :)


 

 

Article has been written for you by Michal Zurek
Avatar
Do you like this article?
No one has rated this quite yet, be the first one!
Thumbnail
Previous article
Loops in VB.NET
Thumbnail
All articles in this section
Visual Basic (VB.NET) basic constructs
Thumbnail
Next article
Arrays in VB.NET
Activities (3)

 

 

Comments

Avatar
Fabrice Bouka
Member
Avatar
Fabrice Bouka:27. February 21:51

Hi,
I've tried to make some changes in the last code of the lesson 7. Please, could check it? Thanks!

Module Module1

    Sub Main()

        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
            Console.WriteLine()

            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 = "yes"
                        validChoice = True
                        Console.WriteLine()
                    Case "n"
                        goOn = "no"
                        validChoice = True
                        Console.WriteLine()
                    Case Else

                        Console.WriteLine("Invalid option, please enter yes/no")
                End Select
            End While
        End While
        Console.WriteLine("Thank you for using our calculator. Press any key to end the program.")
        Console.ReadKey()
    End Sub
End Module
Edited 28. February 5:06
 
Reply 27. February 21:51
Avatar
David Capka
ICT.social team
Avatar
Replies to Fabrice Bouka
David Capka:28. February 5:07

Seems fine to me, good job :)

Reply 28. February 5:07
You can walk through a storm and feel the wind but you know you are not the wind.
To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

2 messages from 2 displayed.