I have a user entered string:
"{0.3064, 15.6497, 60.7668, 52.1362, 76.6645, 97, -15.8315, -6.8806, 5.547, -2.3381, -23.9905, 40.4569, 60.1592, 27.1418, 42.9375, -22.8297, -11.7423, -17.1576, -33.9918, 7.0585}"
and I would like to be able to validate it based on having a "{" at the start, a "}" at the end and twenty comma separated numbers between -1000 and 1000 in between the commas.
I have tried using the like operator as below with no luck. Everything returns False no matter whether it matches the patter or not. How can I validate based on this pattern.
This is what I have tried:
ArrayOk = ArrayValues1txt.Text Like "{[(1000)-1000],[(1000)-1000],[(1000)-1000],[(1000)-1000],[(1000)-1000],[(1000)-1000],[(1000)-1000],[(1000)-1000],[(1000)-1000],[(1000)-1000],[(1000)-1000],[(1000)-1000],[(1000)-1000],[(1000)-1000],[(1000)-1000],[(1000)-1000],[(1000)-1000],[(1000)-1000],[(1000)-1000],[(1000)-1000]}"
If ArrayOk = False Then
MsgBox("Wrong array pattern! Pattern must contain 20 elements and be in the form {#,#}",
MessageBoxButtons.OK, "Bad Array Entered")
GoTo Canceller
Else
End If
You can use RegEx to validate the general pattern of: Are there 20 decimal values separated by commas wrapped in curly brackets?
Dim pattern = "^{((-?\d+(\.\d+)?),\s?){19}(-?\d+(\.\d+)?)}$"
Dim input = "{0.3064, 15.6497, 60.7668, 52.1362, 76.6645, 97, -15.8315, -6.8806, 5.547, -2.3381, -23.9905, 40.4569, 60.1592, 27.1418, 42.9375, -22.8297, -11.7423, -17.1576, -33.9918, 7.0585}"
If (Regex.IsMatch(input, pattern)) Then
End If
Once you validated that it matches the specific pattern, you can validate that the numbers match the numeric range validation by doing the following:
Remove the brackets from the String
Split the string by a comma
Trim any excessive whitespace from the items
Convert the items to fractional values (Double, Decimal, etc.)
Check if the items are within range
You can do a lot of those steps using LINQ which would make it much more concise:
Dim pattern = "^{((-?\d+(\.\d+)?),\s?){19}(-?\d+(\.\d+)?)}$"
Dim input = "{0.3064, 15.6497, 60.7668, 52.1362, 76.6645, 97, -15.8315, -6.8806, 5.547, -2.3381, -23.9905, 40.4569, 60.1592, 27.1418, 42.9375, -22.8297, -11.7423, -17.1576, -33.9918, 7.0585}"
If (Regex.IsMatch(input, pattern)) Then
input = input.Replace("{", String.Empty).Replace("}", String.Empty)
Dim items = input.Split(",")
Dim convertedItems = items.Select(Function(item) Convert.ToDouble(item.Trim())).ToArray()
If (convertedItems.All(Function(item) item >= -1000 AndAlso item <= 1000)) Then
Console.WriteLine("All of the items are within -1000 and 1000")
End If
End If
Here is a live demo: fiddle
I used String.StartsWith and String.EndsWith to test for the braces. Next I chopped them off with Substring. I then split the string by commas. I checked whether there were exactly 20 elements.
If we get this far, I loop through each element. Trim off any leading or trailing spaces and change it to a double. Then I can do the number comparison.
Private Function ValidateArray(input As String) As Boolean
If Not input.StartsWith("{") OrElse Not input.EndsWith("}") Then
Return False
End If
input = input.Substring(1, input.Length - 2)
Dim splits = input.Split(","c)
If splits.Length <> 20 Then
Return False
End If
For Each n In splits
Dim dbl = CDbl(n.Trim)
If dbl > 1000 OrElse dbl < -1000 Then
Return False
End If
Next
Return True
End Function
Usage:
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim IsValid = ValidateArray("{0.3064, 15.6497, 60.7668, 52.1362, 76.6645, 97, -15.8315, -6.8806, 5.547, -2.3381, -23.9905, 40.4569, 60.1592, 27.1418, 42.9375, -22.8297, -11.7423, -17.1576, -33.9918, 7.0585}")
MessageBox.Show(IsValid.ToString)
End Sub
This code is from a subroutine that checks if a text box entry fits the criteria specified (an integer between 1 and 100).
The first IF statement should check if it is not a numerical entry. If it is not numerical then the contents of the text box should be set blank so that a number can be entered.
The second IF statement should check if the number is larger than 100. If it is then the contents of the text box should be set blank so that an appropriate number can be entered.
The Third IF statement should check if the number is smaller than 1. If it is then the contents of the text box should be set blank so that an appropriate number can be entered.
Finally the contents of the box should be set as the variable.
I initially programmed the first IF statement on its own and it worked. But upon adding the others my program would crash when I typed anything into the text box and the error was as stated in my title. I have looked at multiple solutions and have found nothing for almost 2 days that fixed the problem.
Any suggestions would be appreciated.
Public Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles NumQTextBoxInput.TextChanged
'Check if input is numeric
If Not IsNumeric(NumQTextBoxInput.Text) Then NumQTextBoxInput.Text = ""
If (NumQTextBoxInput.Text > 100) Then
NumQTextBoxInput.Text = ""
End If
If (NumQTextBoxInput.Text < 1) Then
NumQTextBoxInput.Text = ""
End If
ArchwayComputingExamCreator.GlobalVariables.NumOfQuestions = NumQTextBoxInput.Text
'Setting the variable to the contense
End Sub
You should always use the appropriate parse function when accepting text for numbers.
Public Sub TextBox1_TextChanged(sender As Object, e As EventArgs) Handles NumQTextBoxInput.TextChanged
Dim Value as integer
If Not Integer.TryParse(NumQTextBoxInput.text, Value) OrElse Value < 1 OrElse Value > 100 Then NumQTextBoxInput.Text = ""
... no idea if the archway bit is really what you wanted so left that out ....
End Sub
In this operation:
If Not IsNumeric(NumQTextBoxInput.Text) Then NumQTextBoxInput.Text = ""
Any time the input is not numeric, you set it to a value which is still not numeric. So any numeric comparison will fail:
If (NumQTextBoxInput.Text > 100)
Maybe you meant to set the value to some numeric default?:
If Not IsNumeric(NumQTextBoxInput.Text) Then NumQTextBoxInput.Text = "0"
Or just exit the method entirely when it's not numeric?:
If Not IsNumeric(NumQTextBoxInput.Text) Then
NumQTextBoxInput.Text = ""
Return
End If
Or perhaps something else? However you modify your logic, the point is that you can't perform numeric comparisons on non-numeric strings.
I'm trying to write a VBA code with if the i get an error.
I want the code to check if one of the values ("S925,S936,S926,G") is not on cell 10.
Sub checklist()
Dim x
Dim LineType
NumRows = Cells(Rows.Count, "j").End(xlUp).Row
For x = 2 To NumRows
If LineType = "G" Then
If Not InStr("S925,S936,S926,G", cellsCells(x, 10).Value) Then
cells Cells(x, 52).Interior.Color = rgbCrimson
cells Cells(x, 52).Value = "G"
End If
End If
End If
Next x
End Sub
This won't cause an error but it will cause issues with your program so I'll explain it.
InStr doesn't return a Boolean but the index of the first occurrence of the search string. If the string isn't found it returns 0.
For example InStr("12345", "23") will return 2.
Because everything except 0 is cast as True, something like If Instr(....) Then will perform as expected.
However if you use If Not InStr(....) Then something else can/will happen
If Not InStr("12345", "23") Then
Debug.Print "test evaluated as True!"
End If
this prints test evaluated as True! even though "23" is contained in "12345". This is not because InStr returned False though. We can replace the InStr expression with 2 to better understand:
Debug.Print 2 '2 (duh)
Debug.Print CBool(2) 'True (2 converted to Boolean)
Debug.Print Not 2 '-3
Debug.Print CBool(Not 2) 'True (-2 converted to Boolean)
Wy is Not 2 evaluated as -3? That's because the 2 isn't converted to Boolean before Not is applied but the Not is applied bit-wise to the 2, which means every bit is flipped. So 2 (0010) becomes 1101 which is -3 because the computer uses the two's complement to express negative numbers. (Actually more bits are used for Integer but it works the same.) As -3 is not 0, it will be converted to True. Since Not 0 will also be evaluated as True (0000 will be converted to 1111 which is -1 as two's complement) the expression Not InStr(...) will always be evaluated as True.
This bit-wise behavior isn't noticed when working with Booleans because they are represented as 0000 and 1111 internally. This also becomes apparent like this:
Debug.Print 1 = True 'False
Debug.Print CBool(1) = True 'True
Debug.Print -1 = True 'True
Debug.Print CBool(-1) = True'True
Debug.Print CInt(True) '-1 (True converted to Integer)
As you can see here, the True is converted to an Integer rather than the Integer being converted to a Boolean for the = comparison.
Long explanation, short fix: Use If InStr(...) > 0 Then instead of If InStr(...) Then and If InStr(...) = 0 Then instead of If Not InStr(...) Then.
PS: This can also cause confusing behavior if you combine two InStr tests with And because And will be applied bitwise as well.
how can i check if a string only contains 4 digit numbers ( or a year )
i tried this
Dim rgx As New Regex("^/d{4}")
Dim number As String = "0000"
Console.WriteLine(rgx.IsMatch(number)) // true
number = "000a"
Console.WriteLine(rgx.IsMatch(number)) // false
number = "000"
Console.WriteLine(rgx.IsMatch(number)) //false
number = "00000"
Console.WriteLine(rgx.IsMatch(number)) // true <<< :(
this returns false when its less than 4 or at characters but not at more than 4
thanks!
I actually wouldn't use a regex for this. The expression is deceptively simple (^\d{4}$), until you realize that you also need to evaluate that numeric value to determine a valid year range... unless you want years like 0013 or 9015. You're most likely going to want the value as an integer in the end, anyway. Given that, the best validation is probably just to actually try to convert it to an integer right off the bat:
Dim numbers() As String = {"0000", "000a", "000", "00000"}
For Each number As String In numbers
Dim n As Integer
If Integer.TryParse(number, n) AndAlso number.Length = 4 Then
'It's a number. Now look at other criteria
End If
Next
Use LINQ to check if All characters IsDigit:
Dim result As Boolean = ((Not number Is Nothing) AndAlso ((number.Length = 4) AndAlso number.All(Function(c) Char.IsDigit(c))))
You should use the .NET string manipulation functions.
Firstly the requirements, the string must:
Contain exactly four characters, no more, no less;
Must consist of a numeric value
However your aim is to validate a Date:
Function isKnownGoodDate(ByVal input As String) As Boolean 'Define the function and its return value.
Try 'Try..Catch statement (error handling). Means an input with a space (for example ` ` won't cause a crash)
If (IsNumeric(input)) Then 'Checks if the input is a number
If (input.Length = 4) Then
Dim MyDate As String = "#01/01/" + input + "#"
If (IsDate(MyDate)) Then
Return True
End If
End If
End If
Catch
Return False
End Try
End Function
You may experience a warning:
Function isKnownGoodDate does not return a value on all code
paths. Are you missing a Return statement?
this can be safely ignored.
I have multiple textboxes in a groupbox, and can successfully cycle through them all. However the checkNumbers sub fails to recognise blank/null entries, and also non-numeric characters. The correctValidation boolean should return true if all the criteria are met (no blanks/nulls, and must be a number between 1-20). Any thoughts on how to solve this would be appreciated.
Private Sub checkNumbers()
Try
For Each txt As TextBox In Me.gbTechnical.Controls.OfType(Of TextBox)()
If txt.Text <> "" And IsNumeric(txt.Text) And (Integer.Parse(txt.Text) >= 1 And Integer.Parse(txt.Text) <= 20) Then
correctValidation = True
Else
correctValidation = False
MsgBox("Please ensure all numbers are between 1 and 20")
Exit Sub
End If
Next
Catch ex As Exception
MessageBox.Show("General: Please ensure all numbers are between 1 and 20")
End Try
End Sub
I would use Integer.TryParse and then >= 1 AndAlso <= 20. You could use this LINQ query:
Dim number As Int32
Dim invalidTextBoxes =
From txt In gbTechnical.Controls.OfType(Of TextBox)()
Where Not Integer.TryParse(txt.Text, number) OrElse number < 1 OrElse number > 20
Dim correctValidation = Not invalidTextBoxes.Any()
Note that you should almost always use AndAlso instead of And and OrElse instead of Or since those operators are Is short-circuiting boolean operators. This can be more efficient and - more important - can prevent errors. Consider this:
Dim text = ""
If txt IsNot Nothing And txt.Text.Length <> 0 Then text = txt.Text
This fails if txt is nothing since the second condition is evaluated even if the first already was evaluated to false which causes a NullReferenceException at txt.Text.
if you only want a number value, why don't you try to use NumericUpDown. You can also set the Minimum and Maximum in property or use
NumericUpDown1.Maximum = 20
so, there won't be a need to do checkNumbers.
Or is there any reason that you have to use textbox??