Solved

numeric validation

Posted on 2011-02-28
7
305 Views
Last Modified: 2012-05-11
I have a textbox that receives inches as input.  I only want to allow the user to enter a whole number or a number with a .5 to denote a half inch.  Does anybody have an example of how to validate this?
0
Comment
Question by:oak29
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 2
  • 2
  • 2
  • +1
7 Comments
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 35002104

Dim value As String = Me.textBox1.Text
Dim converted As Decimal

If Decimal.TryParse(value, converted) AndAlso (converted - Int(converted) = 0.5) Then
    MsgBox("Yay!")
End If

Open in new window

0
 
LVL 75

Accepted Solution

by:
käµfm³d   👽 earned 500 total points
ID: 35002119
Correction:
Dim value As String = Me.textBox1.Text
Dim converted As Decimal

If Decimal.TryParse(value, converted) AndAlso ((converted - Int(converted) = 0.5) OrElse (converted - Int(converted) = 0.0)) Then
    MsgBox("Yay!")
End If

Open in new window

0
 
LVL 13

Expert Comment

by:gamarrojgq
ID: 35002200
Hi,

You can do a couple of things, first use a NUMERICAUPDOWN control instead of a textbox, second set the DECIMALSPLACE property to 1, and finally you can put this code in the Validating Event



Dim intPart As Int32
        intPart = Int32.Parse(NumericUpDown1.Value.ToString.Substring(0, NumericUpDown1.Value.ToString.IndexOf(".")))
        If NumericUpDown1.Value > intPart And NumericUpDown1.Value <> (intPart + 0.5) Then
            MsgBox("Only Whole Numbers or Half", MsgBoxStyle.Critical)
            e.Cancel = True
        End If

Open in new window

0
Creating Instructional Tutorials  

For Any Use & On Any Platform

Contextual Guidance at the moment of need helps your employees/users adopt software o& achieve even the most complex tasks instantly. Boost knowledge retention, software adoption & employee engagement with easy solution.

 
LVL 8

Expert Comment

by:PagodNaUtak
ID: 35003349
Try the below code...
Private Sub TextBox1_KeyPress(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress  
        Dim KeyAscii As Short = Asc(e.KeyChar)  
        ' Check if the typed character is a letter.  
        If Char.IsDigit(e.KeyChar) = False And _  
         Char.IsControl(e.KeyChar) = False Then  
            e.Handled = True  
        End If  
        ' Check if the typed character is a period.  
        If KeyAscii = 46 Then  
            e.Handled = False  
        End If  
    End Sub

Open in new window

0
 
LVL 5

Expert Comment

by:andr_gin
ID: 35005585
1.) Using code like this can be dangerous as other countries use different formatting for numeric values. For example the German standard is a comma instead of a point. If you parse (4711.815) you get 47110815, because the dot is interpreted as thousand delimiter => not good for a finance application ;-)

2.) With this code you cant the sure, if the user enters two dots. There are some conditions you cannot check with the KeyPress. For example the Text "4711." is not valid, but the text "4711.5" is valid. So typing the dot will create a temporary invalid number, even if you do it the right way.

3.) You can use a masked textbox for helping the user to enter the correct format, but you have to check the data, when parsing it.

4.) Be sure to not check for =, when using decimal values. Because of the limited amount of binary digits a value like 0.1 will be stored as 0.1000000000000001 or 0.099999999999. For 0.5 values you do not have this problem directly, but after the first calculation.

5.) I would use code like this for the check method. Call this code when parsing the TextBox (Or MaskedTextBox). If you want, you can also call it in the Validating event after the user leaves the TextBox

Dim DoubleValue As DoubleValue
If Double.TryParse(TXT_YourTextBox.Text,DoubleValue Then
     Dim DoubleDoubleValue =DoubleValue*2
    If Math.Abs(DoubleDoubleValue - Math.Round(DoubleDoubleValue,0)) < 0.000001 Then
           MsgBox("Your Value is: " & DoubleValue)
    Else
        MsgBox("Only enter x.0 or x.5")
   EndIf
Else
MsgBox("Invalid Format")
EndIf
0
 
LVL 8

Expert Comment

by:PagodNaUtak
ID: 35005704
@andr qin,

Nice, tips...

I am just a little curios why need this line of code?
Dim DoubleDoubleValue =DoubleValue*2
0
 
LVL 5

Expert Comment

by:andr_gin
ID: 35005792
Well you want the user to enter only full or halfs, so I double it. Then it must be in integer value. So I compare the rounded value with the original value and if the difference is less then 10^-6 I accept it.

If it is not exactly 0.5 you can also write it this way:

Private Const LittleDouble as Double=0.000001

Dim DoubleValue As DoubleValue
If Double.TryParse(TXT_YourTextBox.Text,DoubleValue Then
     Dim Difference = Math.Abs(DoubleValue - Math.Round(DoubleValue,0))
    If Differnce < LittleDouble OrElse (Difference >= 0.5-LittleDouble  AndAlso Difference <= 0.5+LittleDouble) Then
           MsgBox("Your Value is: " & DoubleValue)
    Else
        MsgBox("Only enter x.0 or x.5")
   EndIf
Else
MsgBox("Invalid Format")
EndIf
0

Featured Post

[Live Webinar] The Cloud Skills Gap

As Cloud technologies come of age, business leaders grapple with the impact it has on their team's skills and the gap associated with the use of a cloud platform.

Join experts from 451 Research and Concerto Cloud Services on July 27th where we will examine fact and fiction.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article explains how to create and use a custom WaterMark textbox class.  The custom WaterMark textbox class allows you to set the WaterMark Background Color and WaterMark text at design time.   IMAGE OF WATERMARKS STEPS Create VB …
Creating an analog clock UserControl seems fairly straight forward.  It is, after all, essentially just a circle with several lines in it!  Two common approaches for rendering an analog clock typically involve either manually calculating points with…
Add bar graphs to Access queries using Unicode block characters. Graphs appear on every record in the color you want. Give life to numbers. Hopes this gives you ideas on visualizing your data in new ways ~ Create a calculated field in a query: …
Sometimes it takes a new vantage point, apart from our everyday security practices, to truly see our Active Directory (AD) vulnerabilities. We get used to implementing the same techniques and checking the same areas for a breach. This pattern can re…

617 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question