I have 3 textboxes (day, month, year) and I want to check if input is e.g. day has to be from 1 to 31 and so on.
My code is:
If InputDan.Text < "1" Or InputDan > "31" Then Warning.Text = "Not a valid day input." Else Warning.Text = ""
Also I have day and month input limited to 2 characters and year to 4.
It works fine with numbers from 10 to 31 and it properly puts an warning message when input is 0 or 32 and on.
Here's the problem...
When I put in numbers from 4 to 9 it puts on a warning message, as I figured out later that program considers empty space after one character input as 0.
So if I enter 4 the program will read it as 40, and so on.
Can I solve this problem with converting String input as Int somehow?
You need to parse the numbers to integer before you can compare them, otherwise >"11" will compare them alphabetically and not by their numerical order.
Dim day As Integer
Dim valid As Boolean = Int32.TryParse(InputDan.Text, day)
Now you know if that input was a correct number and you could show a warning if it was not.
I would suggest a different approach to check whether or not the input was a correct day since you must take the number of days in that month into account(also leap years, different calendars etc). So use the current culture's calendar and look if the number of days is correct for the given month in this way:
Dim daysInMonth = CultureInfo.CurrentCulture.Calendar.GetDaysInMonth(year, month)
If day > daysInMonth OrElse day < 1 Then
' show warning '
End If
(assuming you have already checked the year and month part with Int32.TryParse)
Better than doing this from the code behind, asp.net has already validations here is an example of a textbox that represents the day, and it has to be between 1 and 31:
<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
<asp:RangeValidator ID="RangeValidator1" runat="server"
ErrorMessage="You have to insert a valid day" ControlToValidate="TextBox2" MaximumValue="31" MinimumValue="1"></asp:RangeValidator>
check it out
Your problem is, that "9" (the string) IS "larger" than "31". Because sorting is done on the first char, then the second and so on.
Dim Value As Integer
' is there an (integer) NUMBER in the textbox?
If Integer.TryParse(InputDan.Text, Value) Then
If Value > 0 AndAlso Value < 31 Then
' do something
Else
MessageBox.Show("please enter a number!")
End If
Else
MessageBox.Show("please enter a number!")
End If
With "TryParse" you can test if a String can be converted to an Integer (or Double, Single, whatever implements a TryParse method) and if it can be converted, the value is stored in the second parameter.
You should use Strict on" to avoid the coding problems - basically you are comparing strings against each other. They do NOT behave like Integers for comparisons.
Try like this: (Assuming framework above/or 3.5)
If Not IsNumeric(InputDan.Text) OrElse _
Not Enumerable.Range(1, 31).Contains(CInt(InputDan.Text)) Then
Warning.Text = "Not a valid day input."
Else
Warning.Text = ""
End If
It will first validate the input must be a number and then will validate if it lies within range of 1 and 31. I assume Days can not be 1.5 so I called CInt.
OrElse is what we call ShortCircuit. The second condition will not evaluate if the first one failed.
Related
Hey everyone I am working on an assignment where i have to validate the user input data. When asking my instructors if i can use a IsNumeric to validate a range between two numbers he just said yes and did not show me how.
Now I know you can validate using if statements , and i have several doing so with a basic:
if hours < 0 then
Messagebox("Please enter a value greater than 0" "Input Value to
low" messagebox.buttons retry/cancel) ''something like that
Elseif hours > 23 then
Messagebox( "please enter a value less than 23" "Input Value to
high" messagebox.buttons retry/cancel)
End if
I even asked him if i can use a AND in the if statement to range the data. Again yes with no example
Example that i had in mind
If hours < 0 AND hours > 23 then
'' continue processing
Else
Messagebox("Please enter a Value between 0 and 23" "Input
value
out of range" messagebox.buttons retry/cancel)
End if
In response to your example you can try this:
If isnumeric(hours) then
If hours < 0 AND hours > 23 then
'' continue processing
Else
MessageBox.Show("Input value out of range",
"Please enter a Value between 0 and 23",
MessageBoxButtons.RetryCancel)
End if
End if
IsNumeric() is old... modern practice would tend to use Integer.TryParse() or Double.TryParse(), depending on what kind of value you need. You can also use CInt() or Convert.ToInt32(), but when you know you start with a string, parsing is the best choice.
But what concerns me is you should also have Option Strict turned on, or at least Option Infer. Anything else is really poor practice. With that in mind, look at this code:
Dim hours As String = GetSomeValueFromUser()
If IsNumeric(hours) Then
If hours < 0 Or hours > 23 Then 'a value can never be both negative *and* greater than 24
'...
End
End If
In any sensible project, that should be a compiler error, because it uses a string value (hours) as if it's a number. It doesn't matter that you checked with IsNumeric() first. If you're using Option Strict, as you should be, that's still an error.
This is much better practice:
Dim hours As String = GetSomeValueFromUser()
Dim hrs As Integer
If Integer.TryParse(hours, hrs) AndAlso hrs>= 0 AndAlso hrs <= 23 Then
'code here
Else
MessageBox.Show("Please enter a Value between 0 and 23" "Input value out of range", MessageBoxButtons.RetryCancel)
End If
One additional thing here: NEVER declare a variable for Function without an explicit type known to the compiler. Option Infer can muddy the waters there somewhat, but generally the type of a variable should always be known and fixed.
I have 2 textboxes which inputs 2 values from the user and compares the first value with the second. If the first value is less than the second value, it enters the loop where the user has to input the values again.
The problem I am getting is if I input 10 and 9.9 in the text boxes, it is entering into the loop and saying that 10 is less than 9.9. This happens only with 10,100 and 1000. Please help.
I even tried defining Long type variables for both the integers and assigned them and compared them, excel just hangs. Please help
Here is the code below.
If Mean < LSLValue Then
MsgBox "Please enter a numeric value greater than LSL as Nominal Value"
Me.DimnTxt.Value = InputBox("Enter the Nominal")
Me.LSLTxt.Value = InputBox("Enter the LSL")
Mean = Me.DimnTxt.Value
LSLValue = Me.LSLTxt.Value
End If
Loop Until Mean >= LSLValue
May be because you are comparing text instead of number.
Try convert to number then compare. EG:
if CDbl(Textbox1.value) < CDbl(Textbox2.value) then
'....
end if
I would like my function to follow some convention to check if my ticket number needs formatting or not.
If the convention is not met, then I would like to make some changes to the ticket number.
Ticket number 19K3072216 needs to be formatted to this 19-K3-07-002216 because it does not meet the following conditions.
My function should do the following.
Check if the 1st 2 digits has a value 0 - 9 (numeric)
Check if the 3rd digit has a value of A to Z
Check if the 4th digit has a value 0 - 9 (numeric)
Check if the 5th and 6th digits has a date value (e.g.2 digit year - 17, 90, 15 etc)
Check if the next 6 digits i.e. 7th - 12th digits are numeric.
Because ticket number 19K3072216 does not meet the above conditions, I would like my function to format it to look like this 19-K3-07-002216
The string strTicketNumber should return formatted ticket number 19-K3-07-002216
My vb.net function
Public Class Ticket_Code
Public Shared Sub main()
Dim strTicketNumber As String = FixTicketNumber("19K3072216")
End Sub
Public Shared Function FixCaseNumber(ByVal astrCaseNumber As String) As String
Dim strCaseNumber As String = Replace(astrCaseNumber, "-", "")
'Determine if ticket number is formatted
How do I do this?
'If ticket number is formatted add 2 zeros
'How do I do this?
'Else return unchanged
'If ticket number is already formatted, just returned the number (original number)
Return strCaseNumber
End Function
End Class
It will really depend on your input and how different from the example it can be.
For instance will invalid input always be in the same format 19K3072216or is there the chance it will be all digits, all letters, less/more than 10 characters long etc. All of these rules need to be considered and handled as necessary.
If the input will be from a user, never trust it and always assume it is the furthest from valid as possible. If the app can handle that case it can handle everything else
Something like this should get you started:
Public Sub Main()
Dim strTicketNumber As String = FixTicketNumber("19-K3-07-002216") ' or 19K3072216
Console.WriteLine(strTicketNumber)
Console.ReadKey()
End Sub
Private Function FixTicketNumber(p1 As String) As String
Dim fixed As String = ''
Dim valid As Boolean = checkTicketNumber(p1)
If valid Then
Return p1 ' Ticket number is valid, no transformation needed
Else
'Assume invalid input will always be 10 characters (e.g. 19K3072216)
'Split the input and Step through each rule one at a time
'returning the necessary result/format string as you go
'#1 Check if the 1st 2 digits has a value 0 - 9 (numeric)
Dim ruleOne As String = p1.Substring(0, 2)
'perform isNumeric, concatenate to fixed if everything is ok
'fixed += ruleOne+"-"
'#2 Check if the 3rd digit has a value of A to Z
Dim ruleTwo As String = p1.Substring(3, 1)
'check if its a letter, concatenate to fixed if everything is ok
'... same for all the rules
End If
End Function
Private Function checkTicketNumber(p1 As String) As Boolean
'See if the input matches the rules
'Check if the 1st 2 digits has a value 0 - 9 (numeric)
'Check if the 3rd digit has a value of A to Z
'Check if the 4th digit has a value 0 - 9 (numeric)
'Check if the 5th and 6th digits has a date value (e.g.2 digit year - 17, 90, 15 etc)
'Check if the next 6 digits i.e. 7th - 12th digits are numeric.
Dim pattern As String = "\d{2}-[A-Z]\d-\d{2}-\d{6}"
Dim match As Match = Regex.Match(p1, pattern)
Return match.Success
End Function
It is hard to produce a fully working solution as there are too many unknowns about the input as an outsider.
I have a grid view ,,in grid view 5 th and 6 th column i have only enter numeric data,i mean mobile number and land number ,
i given code like this in gridview_cellvalidating event
If e.ColumnIndex = 5 Or e.ColumnIndex = 6 Then
Dim i As Integer
If Not String.IsNullOrEmpty(e.FormattedValue) AndAlso Not Integer.TryParse(Convert.ToString(e.FormattedValue), i) Then
e.Cancel = True
MsgBox("Please Enter Numeric")
Else
End If
End If
but this code is working if i enterd only 10 digit number,in 6 th column of datagrid view i have to enter country code also 'So i am giving number somthing like this: 971563158147.
this number is coming more than 10 digit,so this time showing message box("Please Enter Numeric")
how i can resolve this issue?
If you want to only allow all-numeric input up to, say, 12 characters, and don't actually care about parsing it as a number, you could use regular expressions. Pseudo-code:
Imports System.Text.RegularExpressions
Regex regex = new Regex(#"\d{12}");
If Not String.IsNullOrEmpty(e.FormattedValue) AndAlso Not regex.IsMatch(e.FormattedValue)
This will ensure that you get a non-empty input which is composed of exactly 12 digits. Now, if you wanted to allow, say, between 8 to 12 digits, you would just change the regex to:
Regex regex = new Regex(#"\d{8,12}");
To address your original query, 971563158147 is larger than the maximum value for Int32, so there will be overflow when parsing it. That's the source of your error.
You are running into the maximum value for an Integer when the input number is larger than 2,147,483,647.
You could instead use a regular expression to validate the input or use Int64.TryParse.
Check the MaxInputLength of the 6th cell, change it to required length if the field holds 10
I am looking for assistance with my program. I have a user enter 6 digits; of these the input must be alpha-numeric. I have already done the TryParse method for the numbers, but I am looking for validation that the string contains an alpha.
I am aware you must use ASC but am unsure both on how to develop a range say Asc((Chr(65) <= Chr(90))) (between A-Z) and also to say (IF my input contains any of these values within the 6 characters, to return true. I keep getting an overload resolution and wish to know how to properly code so the variables are accurate.
This is a great place to use a regular expression
Dim input = ...
If Regex.IsMatch(input, "^\w+$") AndAlso input.Length = 6 Then
' It's a match
Else
' It's not a match
End If
This will match any string which consists only of letters that has length equal to 6
You can iterate through each char and check if it's a letter. If so, set a flag to true.
Dim containsAlpha Boolean = False
For i As Integer = 0 To input.Length - 1
If Char.IsLetter(input(i)) Then
containsAlpha = True
Exit For
End If
Next
Char.IsLetter will match Unicode alphabetic letters, so not just Latin A-Z (which may or may not be what you actually want).