locked
Text Box input validation RRS feed

  • Question

  • HI,

    I am developing a program that receives input data from many textboxes. This is fine but I need to validate the data immediately the user leaves text box1 and before he /she goes to text box2 etc.

    I want to validate the data immediately instead of waiting until the user clicks a button.

    How can I do this?

    Karlap


    Karl A Phelan

    Tuesday, March 12, 2013 9:54 PM

Answers

  • Hi,

    you can use the "LostFocus" event!
    Any time the user jumps to another control (e.g. Textbox2)  you can handle this event. At this point you can validate the user input and do some actions like set the focus back to the effected textbox or prompting a message.

    You have many textboxes, OK! In this case I would suggest to do it with the following sub:

    Private Sub ValidateTextboxes(sender as Object, e as EventArgs) Handles Textbox1.TextChanged, Textbox2.TextChanged
    
    'Do some action...
    
    End Sub

    In case you need different validations for each Textbox you can do this:

    Private Sub ValidateTextboxes(sender as Object, e as EventArgs) Handles Textbox1.TextChanged, Textbox2.TextChanged
    
    Select Case True
       Case sender Is Me.Textbox1
          'Validate Textbox1...
       Case sender Is Me.Textbox2
          'Validate Textbox2...
    End Select
    
    End Sub

    
    
    • Edited by DeveloperGermany Tuesday, March 12, 2013 10:23 PM
    • Marked as answer by Karlap Thursday, March 14, 2013 6:42 PM
    Tuesday, March 12, 2013 10:21 PM
  • Karlap

    See if you get any tips from the following template. This example is for a multiline textbox - whenever you press enter the cursor goes to a new line and validation occurs. If you click in text to move the text cursor - validation occurs.

    Public Class Form5
        Dim H As String 'history of TextBox1
        Dim S As String 'test string
        Dim F As Boolean ' validation success flag
    
        Private Sub TextBox1_Click(sender As Object, e As System.EventArgs) Handles TextBox1.Click
            tb1validate()
            If F Then ToolTip1.SetToolTip(TextBox1, TextBox1.Text)
        End Sub
    
        Private Sub TextBox1_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
            If e.KeyChar = ChrW(Keys.Enter) Then
                tb1validate()
                If F Then ToolTip1.SetToolTip(TextBox1, TextBox1.Text)
            End If
            'If e.KeyChar = ChrW(Keys.Enter) Then
            '    e.Handled = True
            '    Textbox2.Select()
            'End If
        End Sub
    
        Private Sub TextBox1_Leave(sender As Object, e As System.EventArgs) Handles TextBox1.Leave
            tb1validate()
            If F Then ToolTip1.SetToolTip(TextBox1, TextBox1.Text)
        End Sub
    
        Sub tb1validate()
            F = False
            S = TextBox1.Text
            If S = H Then F = True : Exit Sub
            '
            'put all your validation code here
            '
            'If <at any time validation is fail> Then Goto lbl
            '
            'diagnosis 1
            '
            'diagnosis 2 
            '
            '
            'if program flow gets to here  - then validation success
            F = True : TextBox1.Text = S : H = S
            Exit Sub
    lbl:    'validation failed
            TextBox1.Text = H
            TextBox1.SelectionStart = H.Length
            Beep()
        End Sub
    End Class

    the commented out section in _KeyPress event is an example of a single line textbox - when you press enter - validation occurs - and focus changes to another control.


    Leon C Stanley - - A dinky di VB'er - -


    • Edited by LeonCS Wednesday, March 13, 2013 7:18 AM
    • Marked as answer by Karlap Thursday, March 14, 2013 6:41 PM
    Wednesday, March 13, 2013 7:15 AM

All replies

  • Hello Karlap,

    HI,

    I am developing a program that receives input data from many textboxes. This is fine but I need to validate the data immediately the user leaves text box1 and before he /she goes to text box2 etc.

    I want to validate the data immediately instead of waiting until the user clicks a button.

    How can I do this?

    Karlap


    Karl A Phelan

    Validating or Validated with the events of the TextBox control more information can be found below

    Validating http://msdn.microsoft.com/en-us/library/system.windows.forms.control.validating.aspx

    Validated http://msdn.microsoft.com/en-us/library/system.windows.forms.control.validated.aspx

    Regards.


    • Edited by Carmelo La Monica Tuesday, March 12, 2013 10:01 PM
    • Proposed as answer by jwavila Tuesday, March 12, 2013 10:29 PM
    Tuesday, March 12, 2013 10:00 PM
  • Hi,

    you can use the "LostFocus" event!
    Any time the user jumps to another control (e.g. Textbox2)  you can handle this event. At this point you can validate the user input and do some actions like set the focus back to the effected textbox or prompting a message.

    You have many textboxes, OK! In this case I would suggest to do it with the following sub:

    Private Sub ValidateTextboxes(sender as Object, e as EventArgs) Handles Textbox1.TextChanged, Textbox2.TextChanged
    
    'Do some action...
    
    End Sub

    In case you need different validations for each Textbox you can do this:

    Private Sub ValidateTextboxes(sender as Object, e as EventArgs) Handles Textbox1.TextChanged, Textbox2.TextChanged
    
    Select Case True
       Case sender Is Me.Textbox1
          'Validate Textbox1...
       Case sender Is Me.Textbox2
          'Validate Textbox2...
    End Select
    
    End Sub

    
    
    • Edited by DeveloperGermany Tuesday, March 12, 2013 10:23 PM
    • Marked as answer by Karlap Thursday, March 14, 2013 6:42 PM
    Tuesday, March 12, 2013 10:21 PM
  • Karlap

    See if you get any tips from the following template. This example is for a multiline textbox - whenever you press enter the cursor goes to a new line and validation occurs. If you click in text to move the text cursor - validation occurs.

    Public Class Form5
        Dim H As String 'history of TextBox1
        Dim S As String 'test string
        Dim F As Boolean ' validation success flag
    
        Private Sub TextBox1_Click(sender As Object, e As System.EventArgs) Handles TextBox1.Click
            tb1validate()
            If F Then ToolTip1.SetToolTip(TextBox1, TextBox1.Text)
        End Sub
    
        Private Sub TextBox1_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
            If e.KeyChar = ChrW(Keys.Enter) Then
                tb1validate()
                If F Then ToolTip1.SetToolTip(TextBox1, TextBox1.Text)
            End If
            'If e.KeyChar = ChrW(Keys.Enter) Then
            '    e.Handled = True
            '    Textbox2.Select()
            'End If
        End Sub
    
        Private Sub TextBox1_Leave(sender As Object, e As System.EventArgs) Handles TextBox1.Leave
            tb1validate()
            If F Then ToolTip1.SetToolTip(TextBox1, TextBox1.Text)
        End Sub
    
        Sub tb1validate()
            F = False
            S = TextBox1.Text
            If S = H Then F = True : Exit Sub
            '
            'put all your validation code here
            '
            'If <at any time validation is fail> Then Goto lbl
            '
            'diagnosis 1
            '
            'diagnosis 2 
            '
            '
            'if program flow gets to here  - then validation success
            F = True : TextBox1.Text = S : H = S
            Exit Sub
    lbl:    'validation failed
            TextBox1.Text = H
            TextBox1.SelectionStart = H.Length
            Beep()
        End Sub
    End Class

    the commented out section in _KeyPress event is an example of a single line textbox - when you press enter - validation occurs - and focus changes to another control.


    Leon C Stanley - - A dinky di VB'er - -


    • Edited by LeonCS Wednesday, March 13, 2013 7:18 AM
    • Marked as answer by Karlap Thursday, March 14, 2013 6:41 PM
    Wednesday, March 13, 2013 7:15 AM
  • Thank you Developer Germany - that is what i wanted.

    It worked very well

    Karlap


    Karl A Phelan

    Thursday, March 14, 2013 6:44 PM
  • Just by the way : -

    My previous example is flawed because the tooltip is too dominating - and would be annoying.

    Following example is better.

    Public Class Form5 ' textbox input validation
        Dim H As String 'history of TextBox1
        Dim S As String 'test string
    
        Private Sub TextBox1_Click(sender As Object, e As System.EventArgs) Handles TextBox1.Click
            tb1validate()
        End Sub
    
        Private Sub TextBox1_Enter(sender As Object, e As System.EventArgs) Handles TextBox1.Enter
            ToolTip1.SetToolTip(TextBox1, "")
        End Sub
    
        Private Sub TextBox1_KeyPress(sender As Object, e As System.Windows.Forms.KeyPressEventArgs) Handles TextBox1.KeyPress
            If e.KeyChar = ChrW(Keys.Enter) Then
                tb1validate()
            End If
            'If e.KeyChar = ChrW(Keys.Enter) Then      |Use this instead
            '    e.Handled = True                      |if single line
            '    Textbox2.Select()                     |textbox.
            'End If                                    |
        End Sub
    
        Private Sub TextBox1_Leave(sender As Object, e As System.EventArgs) Handles TextBox1.Leave
            tb1validate()
            ToolTip1.SetToolTip(TextBox1, H)
        End Sub
    
        Sub tb1validate()
            S = TextBox1.Text
            If S = H Then Exit Sub
            '
            'put all your validation and auto-correction code here
            '
            'If <at any time validation is fail> Then Goto lbl
            '
            'diagnosis 1
            '
            'diagnosis 2 
            '
            '
            'if program flow gets to here  - then validation success
            TextBox1.Text = S : H = S
            Exit Sub
    lbl:    'validation failed
            TextBox1.Text = H
            TextBox1.SelectionStart = H.Length
            Beep()
        End Sub
    End Class

    I always welcome any criticism of my code method or otherwise. 

    Thanks


    Leon C Stanley - - A dinky di VB'er - -

    Friday, March 15, 2013 7:42 AM
  • Karl,

    Let me suggest that you reconsider the event to use.

    If you using the .Validating event, as Carmello suggested, it offers you the ability to 'lock the user into the control' until they modify it to something correct.

    Typically you'd use this in conjunction with an ErrorProvider to show the user what's wrong and possibly offer a solution to them, and by setting e.Cancel = True, they can't leave the control until it passes all of the tests that you put in the .Validating code. As an example:

    In that particular one, I’m using the same sub to handle the .Validating event of all three TextBoxes as shown below:

    .Validating Event

    Private Sub Parameter_Validating(ByVal sender As Object, ByVal e As System.ComponentModel.CancelEventArgs) _ Handles tb_SCT.Validating, tb_SST.Validating, tb_MassFlow.Validating Dim tb As TextBox = DirectCast(sender, TextBox) If tb.Text.Trim <> "" Then Dim tempDbl As Double If Not Double.TryParse(tb.Text, tempDbl) Then ErrorProvider1.SetError(tb, _ "The value that you entered is not" & vbCrLf & _ "a valid number.") e.Cancel = True btn_ShowSeps.Enabled = False Else Select Case tb.Name Case "tb_MassFlow" If tempDbl < 1 Then ErrorProvider1.SetError(tb, _ "The value for the mass flow must be" & vbCrLf & _ "a positive value.") e.Cancel = True btn_ShowSeps.Enabled = False End If Case "tb_SST" If tempDbl < minSST Then ErrorProvider1.SetError(tb, _ "The value for the SST is lower than any" & vbCrLf & _ "applicable Temprite separator allows based." & vbCrLf & _ "on the refrigerant that you've chosen." & vbCrLf & vbCrLf & _ "The minimum allowable SST is " & minSST.ToString("n1") & "° F.") e.Cancel = True btn_ShowSeps.Enabled = False ElseIf tempDbl > maxSST Then ErrorProvider1.SetError(tb, _ "The value for the SST is higher than any" & vbCrLf & _ "applicable Temprite separator allows based." & vbCrLf & _ "on the refrigerant that you've chosen." & vbCrLf & vbCrLf & _ "The maximum allowable SST is " & maxSST.ToString("n1") & "° F.") e.Cancel = True btn_ShowSeps.Enabled = False End If Case "tb_SCT" If tempDbl < minSCT Then ErrorProvider1.SetError(tb, _ "The value for the SCT is lower than any" & vbCrLf & _ "applicable Temprite separator allows based." & vbCrLf & _ "on the refrigerant that you've chosen." & vbCrLf & vbCrLf & _ "The minimum allowable is " & minSCT.ToString("n1") & "° F.") e.Cancel = True btn_ShowSeps.Enabled = False ElseIf tempDbl > maxSCT Then ErrorProvider1.SetError(tb, _ "The value for the SCT is higher than any" & vbCrLf & _ "applicable Temprite separator allows based." & vbCrLf & _ "on the refrigerant that you've chosen." & vbCrLf & vbCrLf & _ "The maximum allowable is " & maxSCT.ToString("n1") & "° F.") e.Cancel = True btn_ShowSeps.Enabled = False End If End Select End If End If End Sub


    If you do use the ErrorProvider, you might also want to clear it whenever the text is changed (since they’re most likely attempting to correct the error):

    .TextChanged Event

    Private Sub Parameter_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) _ Handles tb_SST.TextChanged, tb_SCT.TextChanged, tb_MassFlow.TextChanged If tb_MassFlow.Text.Trim <> "" AndAlso tb_SCT.Text.Trim <> "" AndAlso tb_SST.Text.Trim <> "" Then btn_ShowSeps.Enabled = True Else btn_ShowSeps.Enabled = False End If ErrorProvider1.Clear() With combo_Connection .SelectedIndex = -1 .Items.Clear() .Enabled = False End With With tb_Results .Clear() .Enabled = False End With End Sub


    For what it’s worth. :)


    Please call me Frank :)

    Friday, March 15, 2013 4:01 PM
  • Hy Frank,

    Karl,

    Let me suggest that you reconsider the event to use.

    If you using the .Validating event, as Carmello suggested, it offers you the ability to 'lock the user into the control' until they modify it to something correct.

    +1  , 

    In fact, the above examples are all handled with the suggestion given, and since there no other way :)

    Bye


    Friday, March 15, 2013 4:06 PM
  • Hy Frank,

    Karl,

    Let me suggest that you reconsider the event to use.

    If you using the .Validating event, as Carmello suggested, it offers you the ability to 'lock the user into the control' until they modify it to something correct.

    +1  , 

    In fact, the above examples are all handled with the suggestion given, and since there no other way :)

    Bye




    Please call me Frank :)

    Friday, March 15, 2013 4:08 PM