Still celebrating National IT Professionals Day with 3 months of free Premium Membership. Use Code ITDAY17

x
?
Solved

numeric validation

Posted on 2011-02-28
7
Medium Priority
?
309 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 2000 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
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
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

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Article by: jpaulino
XML Literals are a great way to handle XML files and the community doesn’t use it as much as it should.  An XML Literal is like a String (http://msdn.microsoft.com/en-us/library/system.string.aspx) Literal, only instead of starting and ending with w…
A while ago, I was working on a Windows Forms application and I needed a special label control with reflection (glass) effect to show some titles in a stylish way. I've always enjoyed working with graphics, but it's never too clever to re-invent …
This course is ideal for IT System Administrators working with VMware vSphere and its associated products in their company infrastructure. This course teaches you how to install and maintain this virtualization technology to store data, prevent vuln…
Want to learn how to record your desktop screen without having to use an outside camera. Click on this video and learn how to use the cool google extension called "Screencastify"! Step 1: Open a new google tab Step 2: Go to the left hand upper corn…

688 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