Answered validating negative values

  • Friday, June 08, 2012 2:21 PM
     
      Has Code

    I have a function that allows a user to enter numeric vallues and also a period for the decimal points but I also want to allow for users to enter the minus sign to allow users to enter negative values . How would I go about it.

     Public Function SingleDecimal(ByVal sender As System.Object, ByVal eChar As Char) As Boolean
            Dim chkstr As String = "0123456789."
            If chkstr.IndexOf(eChar) > -1 OrElse eChar = vbBack Then
                If eChar = "." Then
    
                    If CType(sender, Telerik.WinControls.UI.RadTextBox).Text.IndexOf(eChar) > -1 Then
                        Return True
                    Else
                        Return False
                    End If
    
                End If
    
                Return False
            Else
                Return True
            End If
        End Function


    If you think it you can achieve it

All Replies

  • Friday, June 08, 2012 2:33 PM
     
      Has Code
    Public Class NumericTextBox
        Inherits TextBox
        Private SpaceOK As Boolean = False
    
        ' Restricts the entry of characters to digits (including hex),
        ' the negative sign, the e decimal point, and editing keystrokes (backspace).
        Protected Overrides Sub OnKeyPress(ByVal e As KeyPressEventArgs)
            MyBase.OnKeyPress(e)
    
            Dim numberFormatInfo As System.Globalization.NumberFormatInfo = System.Globalization.CultureInfo.CurrentCulture.NumberFormat
            Dim decimalSeparator As String = numberFormatInfo.NumberDecimalSeparator
            Dim groupSeparator As String = numberFormatInfo.NumberGroupSeparator
            Dim negativeSign As String = numberFormatInfo.NegativeSign
    
            Dim keyInput As String = e.KeyChar.ToString()
    
            If [Char].IsDigit(e.KeyChar) Then
                ' Digits are OK
            ElseIf keyInput.Equals(decimalSeparator) OrElse keyInput.Equals(groupSeparator) OrElse keyInput.Equals(negativeSign) Then
                ' Decimal separator is OK
            ElseIf e.KeyChar = vbBack Then
                ' Backspace key is OK
                '    else if ((ModifierKeys & (Keys.Control | Keys.Alt)) != 0)
                '    {
                '     // Let the edit control handle control and alt key combinations
                '    }
            ElseIf Me.SpaceOK AndAlso e.KeyChar = " "c Then
    
            Else
                ' Swallow this invalid key and beep
                e.Handled = True
            End If
    
        End Sub
    
    
        Public ReadOnly Property IntValue() As Integer
            Get
                Return Int32.Parse(Me.Text)
            End Get
        End Property
    
    
        Public ReadOnly Property DecimalValue() As Decimal
            Get
                Return [Decimal].Parse(Me.Text)
            End Get
        End Property
    
    
        Public Property AllowSpace() As Boolean
    
            Get
                Return Me.SpaceOK
            End Get
            Set(ByVal value As Boolean)
                Me.SpaceOK = value
            End Set
        End Property
    End Class
    Example from: http://msdn.microsoft.com/en-us/library/ms229644%28v=vs.80%29.aspx
  • Friday, June 08, 2012 3:46 PM
     
     Answered

    I have a function that allows a user to enter numeric vallues and also a period for the decimal points but I also want to allow for users to enter the minus sign to allow users to enter negative values . How would I go about it.

    I wouldn't do it that way at all. In my opinion - of course do keep that caveat in mind - it's not worth the hassle of trying to make your control work that way and even if you do - I bet you'll miss something.

    Let them type in anything they want - no matter what it is. Then use the control's .Validating event to test for it and if it fails the test, set e.Cancel to true, show them a message, and force them to go back and change it.

    Again ... in my opinion.


    Please call me Frank :)

  • Friday, June 08, 2012 3:56 PM
     
     

    I have a function that allows a user to enter numeric vallues and also a period for the decimal points but I also want to allow for users to enter the minus sign to allow users to enter negative values . How would I go about it.

    I wouldn't do it that way at all. In my opinion - of course do keep that caveat in mind - it's not worth the hassle of trying to make your control work that way and even if you do - I bet you'll miss something.

    Let them type in anything they want - no matter what it is. Then use the control's .Validating event to test for it and if it fails the test, set e.Cancel to true, show them a message, and force them to go back and change it.

    Again ... in my opinion.


    Please call me Frank :)

    Task can be implemented on 100 ways...

    In linked example OP can see how to implement validation using System.Globalization.NumberFormatInfo

  • Friday, June 08, 2012 3:58 PM
    Moderator
     
     

    You are already accepting "3.45.21.456" as valid input... definately not a valid single value....

    I see you are using a non-standard text box so perhaps it is internally limiting the ways in which text can be entered, but typically it isn't feasible to account for all ways in which a value might be entered into a textbox.


    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

  • Friday, June 08, 2012 4:00 PM
     
     
    Maybe OP work on some specific application like calculator.
  • Friday, June 08, 2012 4:00 PM
     
     

    Task can be implemented on 100 ways...

    In linked example OP can see how to implement validation using System.Globalization.NumberFormatInfo

    Well once again, you and I have a difference of opinion. Variety is the spice of life though, so as they say "to each their own".


    Please call me Frank :)

  • Friday, June 08, 2012 4:09 PM
     
     

    Task can be implemented on 100 ways...

    In linked example OP can see how to implement validation using System.Globalization.NumberFormatInfo

    Well once again, you and I have a difference of opinion. Variety is the spice of life though, so as they say "to each their own".


    Please call me Frank :)

    It's not difference in opinion... We don't know why OP needs validation. If OP work on some application like calculator, game etc.. than validation should be implemented in OnKeyDown event handler. If he work on some business application than validation can be implemented in OnValidating event. OP also can combine validations and show some tooltip/baloon from OnKeyDown  even handler but allow user to type anything and to show error message from OnValidating event handler.
  • Friday, June 08, 2012 4:14 PM
     
     
    It's not difference in opinion...

    Everything that you said following that isn't germane. I didn't and won't say that it's not accurate but what IS germane is that clearly you feel "threatened" by someone else saying anything which in any way might make YOUR answer look incorrect.

    For the record here and to put a quick end to this banter, I have NO doubts of your knowledge, skill, deftness, and ability with this; you have proven that time and time again and I have no reservations in saying that you can run circles around me.

    That said, I stated what I BELIEVE TO BE ACCURATE AND CORRECT - as did you.

    Now let's leave it to the OP.

    Please...


    Please call me Frank :)

  • Friday, June 08, 2012 11:02 PM
     
      Has Code

    This would take care of the Keyboard

     Private Sub TextBox1_KeyDown(ByVal sender As Object, ByVal e As System.Windows.Forms.KeyEventArgs) Handles TextBox1.KeyDown
            Dim ValidKey() As Keys = {Keys.OemMinus, Keys.OemPeriod, Keys.Decimal, Keys.Subtract}
            If Not e.KeyCode = Keys.Back Then
                If Char.IsDigit(Chr(e.KeyValue)) OrElse ValidKey.Contains(e.KeyData) Then
                    Dim KV As Integer = e.KeyValue
                    If e.KeyValue > 108 Then KV -= 64
                    If e.KeyValue > 124 Then KV -= 80
                    If (KV = 45 AndAlso TextBox1.Text = "") Then
                        Exit Sub
                    ElseIf (KV = 45 AndAlso Not TextBox1.Text = "") Then
                        e.SuppressKeyPress = True
                    End If
                    If Not IsNumeric(TextBox1.Text & Chr(KV)) Then
                        e.SuppressKeyPress = True
                    End If
                Else
                    e.SuppressKeyPress = True
                End If
            End If
        End Sub

    And this take care of the "Paste"

    Private Sub TextBox1_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox1.TextChanged
            If Not IsNumeric(TextBox1.Text) Then TextBox1.Text = ""
        End Sub

  • Saturday, June 09, 2012 6:01 PM
     
      Has Code

    Another method:

        Function TestDecimal(StrIn As String) As Boolean
            Dim DummyDec As Decimal = 0
            Return Decimal.TryParse(StrIn, DummyDec)
        End Function
    

  • Saturday, June 09, 2012 6:58 PM
     
      Has Code

    Another method:

        Function TestDecimal(StrIn As String) As Boolean
            Dim DummyDec As Decimal = 0
            Return Decimal.TryParse(StrIn, DummyDec)
        End Function

    Devon,

    You're not stating where/how to use that function but that aside, do be aware that the .TryParse method will set the decimal to zero if it fails. So what if the user actually entered zero? How would you be able to know?


    Please call me Frank :)

  • Saturday, June 09, 2012 7:34 PM
     
     

    Devon,

    You're not stating where/how to use that function but that aside, do be aware that the .TryParse method will set the decimal to zero if it fails. So what if the user actually entered zero? How would you be able to know?

    By not ignoring the function return value. :-)

    However, instead of calling TestDecimal, one can simply directly call

       if decimal.tryparse(str, 0) then

       end if


    Armin

  • Saturday, June 09, 2012 7:39 PM
     
     
    By not ignoring the function return value. :-)

    However, instead of calling TestDecimal, one can simply directly call

       if decimal.tryparse(str, 0) then

       end if


    Armin

    Right - and in the other example that I showed the OP this week, I have that (more or less) in the .Validating event.

    Armin! Dang man - you've been hiding ... good to see you around again. :)


    Please call me Frank :)

  • Saturday, June 09, 2012 7:52 PM
     
     

    Frank:

    The return from Decimal.TryParse is Boolean

  • Saturday, June 09, 2012 7:58 PM
     
     

    Frank:

    The return from Decimal.TryParse is Boolean

    Oh I did miss that didn't I *LOL*

    That's what I've used in sample code that I used in the .Validating event that I showed earlier this week to the same OP. I use an ErrorProvider but really any means of communicating the fact that it's not acceptable (a MessageBox even, but I think that's annoying).

    By putting it in the .Validating event, we have the option to "trap" the user into the control, thereby forcing them to change it. Normally I test that it's not String.Empty; if it is then it doesn't test it (but it won't accept it, it just allows the user to continue without being stuck) and I show in the EP that if they want to continue, they need to either provide a valid entry or clear it all together.


    Please call me Frank :)

  • Sunday, June 10, 2012 5:18 PM
     
      Has Code

    Hello Tendemaire,

    I don't see it in this thread, but Visual Basic has already long time (from VB1 to VB11) the function 

    If Isnumeric(TextBox1.Text) then 

    It test all possible numeric values which can exist on a system even the exponent ones.

    Be aware to speak with Herfried E. Wagner that you should not rely on this for key-presses or things like that, the end user can past in values in a textbox, 

    :-)


    Success
    Cor

  • Sunday, June 10, 2012 8:24 PM
     
     

    Armin! Dang man - you've been hiding ... good to see you around again. :)

    Hi Frank,

    good to see you too. :)

    A while ago, it became a kind of overkill, so I (temporarily) quitted participation. Moreover, the usage of these forums is so laborious and time consuming that I didn't want to do it to me anymore. Unfortunatelly nothing changed in the meantime. :-(


    Armin


  • Sunday, June 10, 2012 10:34 PM
     
     
    good to see you too. :)

    A while ago, it became a kind of overkill, so I (temporarily) quitted participation. Moreover, the usage of these forums is so laborious and time consuming that I didn't want to do it to me anymore. Unfortunatelly nothing changed in the meantime. :-(


    Armin


    I understand! :)

    Please call me Frank :)