multiple validation in vb.net [ non 0 and numeric only] - vb.net

How can I multi validate a text box? I only want the user to input integer but the integer shouldn't be 0 or less, how can I do this? This is what I've done:
If Val(txtCopies.Text) <= 0 Then
ErrorProvider1.SetError(txtCopies, "Number should be bigger than 0 ")
If IsNumeric(txtCopies.Text) = False Then
ErrorProvider1.SetError(txtCopies, "Number only")
Else
blabla
End If
End If

If IsNumeric(txtCopies.Text) = True AND CINT(txtCopies.Text) >= 0 Then
'Validation Passed
Else
ErrorProvider1.SetError(txtCopies, "Number should be bigger than 0 ")
End If
there you go, else please explain better
you can also do
If IsNumeric(txtCopies.Text) = True AND CINT(txtCopies.Text) >= 0 Then
'Validation Passed
Else
if not(IsNumeric(txtCopies.Text) = True) then
ErrorProvider1.SetError(txtCopies, "Numbers Only")
else
ErrorProvider1.SetError(txtCopies, "Number should be bigger than 0 ")
end if
End If

It's been a long time since I've done VB but here you go:
It has to be able to convert whatever is in the text box to an integer.
to do this, it checks if the string is numeric, if it is, then the num variable takes its value (so it can be checked). If this value is greater than 0 then it says it's not valid.
It needs to be a nested If statement for this to happen.
Sub OnClick()
Dim str As String
Dim num As Integer
str = TextBox1.Text
If IsNumeric(str) Then
num = str
If num <= 0 Then
TextBox1.Text = "Sorry, not valid"
End If
Else
TextBox1.Text = "Sorry, not a number"
End If
End Sub

Dim intValue As Integer
If Not Integer.TryParse(TxtBox.Text, intValue) OrElse intValue < 0 Then
Else
End If

In your style ..
If Not IsNumeric(txtCopies.Text) And Val(txtCopies.Text) <= 0 Then
ErrorProvider1.SetError(txtCopies, "Number only")
Else
If Val(txtCopies.Text) <= 0 Then
ErrorProvider1.SetError(txtCopies, "Number should be bigger than 0 ")
Else
'Blabla
End If
End If

If interger. Parse(hours Text box. Tex)<=10 then
' code to perform calculation
Else
Message box.Show("Two many hours."," Invalid Data",MessageBoxButtons.OK)
End if

Related

How can i allow only positive number in my code

I'm still new in VB and I have emailed my lecturer but it seems like he is quite busy and didn't have time to reply to me. Can anyone teach me with it?
Dim split = InputTextBox.Text.Split(vbNewLine)
Dim check As Boolean
For i = 0 To split.Length - 1
check = IsNumeric(split(i))
If Not check Then
Exit For
End If
Next
If check Then
FootForm.Show()
Else
MessageBox.Show("Please enter in positive number only")
End If
I am not sure how your value is stored in the form control. The below should help
Dim split as String = InputTextBox.Text.Split(vbNewLine)
Dim parsedint as Integer
If Int32.TryParse(split, parsedint) AndAlso parsedint < 0 Then
MessageBox.Show("Please enter in positive number only")
Else
FootForm.Show()
End If
You can throw a bit of LINQ at the problem:
If InputTextBox.Lines.All(Function(s)
Dim n As Double
Return Double.TryParse(s, n) AndAlso n >= 0.0
End Function) Then
'All lines represent non-negative numbers.
End If
The longhand version would be:
Dim result = True
For Each s In InputTextBox.Lines
Dim n As Double
If Not Double.TryParse(s, n) OrElse n < 0.0 Then
result = False
Exit For
End If
Next
If result Then
'All lines represent non-negative numbers.
End If

If statement true regardless of input

Recently I have been tasked with making a calculator in VB. It must include stuff like logic or denary/binary/hex conversions. When I was making the binary->denary conversion I encountered a thing where an if statement checking if the inputted number is binary always returned true and activated. Here is the code for the binary conversion system: (please forgive me for the goto's)
Private Sub bbin_Click(sender As Object, e As EventArgs) Handles bbin.Click
If temp = IsNumeric(inputbox.Text) Then
MessageBox.Show("Value Not Numeric", "ERROR", MessageBoxButtons.OK)
inputbox.Text = ""
Else
For i = 1 To Len(inputbox.Text)
If Mid(inputbox.Text, i, 1) <> "0" Or Mid(inputbox.Text, i, 1) <> "1" Then
MessageBox.Show("Value Not Binary", "ERROR", MessageBoxButtons.OK)
inputbox.Text = ""
GoTo skipbin
End If
Next
For x = 1 To Len(inputbox.Text)
If Mid(inputbox.Text, x, 1) = "1" Then
decnum = decnum + 2 ^ (Len(inputbox.Text) - (x - 1))
End If
Next
binnum = inputbox.Text
inputbox.Text = ""
End If
textbox.Text = "Dec = " + decnum.ToString + " Bin = " + binnum.ToString + " Hex = " + hexnum.ToString
skipbin:
End Sub
Let me explain:
The inputbox is the place where the user can input the numbers/operations. The first If checks if the value inputed is a number.
Then a check is ran to ensure the number is binary. (this is where im having problems)
The conversion is ran. It doesn't work as intended at the moment, but I'm sure I'll get it working.
Then the binary and denary values get displayed in a second textbox that I use to display the answers.
The problem I'm having is only with this section: (again, forgive me for the goto functions)
For i = 1 To Len(inputbox.Text)
If Mid(inputbox.Text, i, 1) <> "0" Or Mid(inputbox.Text, i, 1) <> "1" Then
MessageBox.Show("Value Not Binary", "I AM ERROR", MessageBoxButtons.OK)
inputbox.Text = ""
GoTo skipbin
End If
Next
It's supposed to check each digit if it's a 1 or a 0, and if not, it displays an error and skips the conversion.
What do I need to change to make the input validation work as intended?
You need And instead of Or.
When you get a bit of code that you can't figure out why it doesn't work, it is often a good idea to make the minimal bit of code that shows the problem - removing everything else can often lead you to the problem.
In this case, to confirm my answer was correct, I used this:
Option Infer On
Option Strict On
Module Module1
Sub Main()
Dim s = "000012"
For i = 1 To Len(s)
Dim c = Mid(s, i, 1)
If c <> "0" And c <> "1" Then
Console.WriteLine("Value Not Binary: {0}", c)
End If
Next
Console.ReadLine()
End Sub
End Module
You can use AndAlso instead of And: it eliminates any unnecessary processing of the clauses (known as short-circuiting). Similarly, there is OrElse instead of Or.
Your problem is your condition result is always true for any binary number.
try this instead
Dim currentChar = CInt(Mid(InputBox.Text, i, 1))
If currentChar <> 0 And currentChar <> 1 Then
MessageBox.Show("Value Not Binary", "ERROR", MessageBoxButtons.OK)
InputBox.Text = ""
GoTo skipbin
End If

Visual Basic Keep validate InputBoxes in a Loop

I am working on a Budget calculator for a class project. Basically everything works great except one little annoying nuance.
When you don't enter a number or you enter a negative number you get an error message. However, when you accidentally type in a letter, get the error, then type in the negative number it just exits, and I want it to show that error and loop back until they enter in a positive number.
I am using VBA in Visual Studio 2012, this is a Windows Form Application.
Dim strEntertainmentHeading As String = "Entertainment Expenses"
Dim strHeading As String = "Budget Alottment"
Dim strNonNumericError As String = "Error - Enter a number for the Expense"
Dim strNegativeError As String = "Error - Enter a positive number for the Expense"
Dim strEntertainmentInput As String = "Enter the amount for Entertainment Expenses"
Dim strEntertainment As String
Dim decEntertainment As Decimal
strEntertainment = InputBox(strEntertainmentInput, strEntertainmentHeading, " ")
Do
If strEntertainment = "" Then
Exit Sub
ElseIf IsNumeric(strEntertainment) Then
decEntertainment = Convert.ToDecimal(strEntertainment)
If decEntertainment >= 0 Then
lstBudget.Items.Add("Entertainment Expense: " & decEntertainment.ToString("C2"))
' Display error message if user entered a negative value
Else
strEntertainmentInput = strNegativeError
End If
Else
strEntertainmentInput = strNonNumericError
End If
If decEntertainment <= 0 Then
strEntertainment = InputBox(strEntertainmentInput, strEntertainmentHeading, " ")
End If
Loop Until IsNumeric(strEntertainment) And decEntertainment >= 0
Of course, you have this problem: decEntertainment is 0 by default and after asking for input the second time, you do not Convert.ToDecimal anymore.
You avoid this type of errors if you adopt a clear coding style, like
Do
strEntertainmentInput = ''
strEntertainment = InputBox(strEntertainmentInput, strEntertainmentHeading, " ")
If Not IsNumeric(strEntertainment) Then
strEntertainmentInput = strNonNumericError
Else
decEntertainment = Convert.ToDecimal(strEntertainment)
If decEntertainment < 0 Then
strEntertainmentInput = strNegativeError
Else
lstBudget.Items.Add("Entertainment Expense: " & decEntertainment.ToString("C2"))
End
End
Loop Until strEntertainmentInput = ''

How do you check if an input is a negative number in VB

I am trying to do some validation which checks if the value in a textbox is an integer then checks if the the value is negative. It correctly checks if the value is an integer but I can't get it to check if the value is negative.
Note: The value being entered is the number of competitions attended so comps = competition etc...
Dim comps As Integer
Dim value As Double
If Integer.TryParse(txtCompsEntered.Text, integer) Then
value = txtCompsEntered.Text
If value < 0 Then
lblcompsatten.ForeColor = Color.Red
txtCompsEntered.ForeColor = Color.Red
lblcompsatten.Text = "No negative numbers"
Else
lblcompsatten.ForeColor = Color.Black
txtCompsEntered.ForeColor = Color.Black
lblcompsatten.Text = ""
End If
lblcompsatten.ForeColor = Color.Black
txtCompsEntered.ForeColor = Color.Black
lblcompsatten.Text = ""
Else
lblcompsatten.ForeColor = Color.Red
txtCompsEntered.ForeColor = Color.Red
lblcompsatten.Text = "Not a number"
End If
I have already looked at this thread but it didn't seem to work
how-to-check-for-negative-values-in-text-box-in-vb
Tryparse will convert the input to an integer if it succeeds - you don't need both the comps and value variables. Here's an example of how it works:
Dim comps As Integer
Dim input As String = "im not an integer"
Dim input2 As String = "2"
'tryparse fails, doesn't get into comps < 0 comparison
If Integer.TryParse(input, comps) Then
If comps < 0 Then
'do something
End If
Else
'I'm not an integer!
End If
'tryparse works, goes into comps < 0 comparison
If Integer.TryParse(input2, comps) Then
If comps < 0 Then
'do something
End If
End If
There are a couple of things off with your code but the main issue is using Integer.TryParse incorrectly.
Incorrect:
Dim value As Double
If Integer.TryParse(txtCompsEntered.Text, integer) Then
value = txtCompsEntered.Text
If value < 0 Then
Correct:
Dim value As Integer
If Integer.TryParse(txtCompsEntered.Text, value) Then
If value < 0 Then
The things to note are that Integer.TryParse will return a boolean value (true if the value can be convertan integer, false if not). It will them dump the converted value into the second parameter you pass into it. In your case, you had 'integer', which is incorrect. You should be passing in a variable and then using that variable for your comparison.
Also, be careful with your types. You have 'value' as a double when you seem to be working with integers.
Maybe try this?
If myinteger.toString.Contains("-") Then
'it's negative
Else
'it isn't
End If
Or even simplier
If myinteger < 0 Then
'it's not negative
Else
'it is negative
End if

Counting blank text box as 0 value While Text Boxes are Empty

I am have written the following code:
Dim i As Integer
Dim pos As Integer = 0
Dim neg As Integer = 0
Dim zer As Integer = 0
Dim TextBoxes() As String = {Val(TextBox1.Text), Val(TextBox2.Text),
Val(TextBox3.Text), Val(TextBox4.Text),
Val(TextBox5.Text), Val(TextBox6.Text),
Val(TextBox7.Text), Val(TextBox8.Text),
Val(TextBox9.Text), Val(TextBox10.Text)}
For i = 0 To 9
If TextBoxes(i) > 0 Then
pos += 1
End If
If TextBoxes(i) < 0 Then
neg += 1
End If
If TextBoxes(i) = 0 Then
zer += 1
End If
Next i
Label4.Text = (pos)
Label5.Text = (neg)
Label6.Text = (zer)
When the program executes and I put some values into the text boxes, the output looks like this. The first text box contains 1 which is positive and the other one contains -1 which is negative. It's working well.
The problem occurs here: the program is counting the empty boxes as 0 and displaying 8 in the total number of zeros. All of the other 8 text boxes were left blank. How can I Fix the issue so that it doesn't count the empty text boxes as 0.
For reference, here is my related, previous problem which has already been solved: Finding String of Substring in VB without using library function
The problem is that you are calling the Val function to get the value in each text box. Val returns 0 if the given text is empty or non-numeric. If you want to check that, you should just store the original strings in the array and then check the value in the loop, like this:
Dim i As Integer
Dim pos As Integer = 0
Dim neg As Integer = 0
Dim zer As Integer = 0
Dim TextBoxes() As String = {TextBox1.Text, TextBox2.Text,
TextBox3.Text, TextBox4.Text,
TextBox5.Text, TextBox6.Text,
TextBox7.Text, TextBox8.Text,
TextBox9.Text, TextBox10.Text}
For i = 0 To 9
If TextBoxes(i) <> String.Empty Then
If Val(TextBoxes(i)) > 0 Then
pos += 1
End If
If Val(TextBoxes(i)) < 0 Then
neg += 1
End If
If Val(TextBoxes(i)) = 0 Then
zer += 1
End If
End If
Next i
Label4.Text = pos.ToString()
Label5.Text = neg.ToString()
Label6.Text = zer.ToString()
However, the Val function is mainly just provided for backwards compatibility with VB6. It will work, but I would recommend using Integer.TryParse instead. Note that I also added ToString to the last three lines. As others have mentioned, it would behoove you to turn Option Strict On.