Reputation: 1325
I should preface this by stating that Visual Basic is not my native language, but I am maintaining a legacy program until which time it can be ported to a different language.
We have a Textbox that is used to enter a quantity. This quantity should be whole numbers only, and this was not being validated. A decimal sneaked into the database and I've been asked to add validation of input. I have tried a Regular Expression.
Function validate_qty(qty As String)
Dim objRegExp As New System.Text.RegularExpressions.Regex("^\d+$")
Dim match As System.Text.RegularExpressions.Match = objRegExp.Match(qty)
If match.Success Then
Return True
End If
Return False
End Function
This is working as far as decimal points is concerned: .1
and 1.0
return false; however, alphanumeric strings such as a1212
or 433498e
return True
Any insight? It would be greatly appreciated.
Upvotes: 0
Views: 14053
Reputation: 3
I also do not see where your error might be on your regex
but try.
btnSave/formload()
dim num as new regex("^\d+$")
if num.Ismatch(yourtextbox1.text) then
yourtextbox1.text="num"
else
yourtextbox.text="invalid num"
exit sub
end if
after this you accept if its correct or terminate by "exit sub " if its incorrect.
Upvotes: 0
Reputation: 19953
Other than shortening the function, I can't see a problem with your RegEx...
Private Function validate_qty(Byval qty As String) As Boolean
Dim objRegExp As New System.Text.RegularExpressions.Regex("^\d+$")
Return objRegExp.Match(qty).Success
End Function
Another option would be to use the static Integer.TryParse
...
Private Function validate_qty(Byval qty As String) As Boolean
Return Integer.TryParse(qty, Nothing)
End Function
Upvotes: 2
Reputation: 69372
You could create a function which returns a "cleaned" string (i.e. one that has any non-digits removed)
Public Function KeepNumbers(input As String) As String
Dim sb As New StringBuilder()
For Each c As Char In input
If [Char].IsDigit(c) Then
sb.Append(c)
End If
Next
Return sb.ToString()
End Function
Upvotes: 0
Reputation: 5719
I dont think you need regex yet ..
Function validate_qty(qty As String) As Boolean
if qty.Contains(".") then Return False
Return IsNumeric(qty)
End Function
Upvotes: 1