locked
VB.NET text box validation

    Question

  • Hi guys, I am making an interface that has to do with sales orders. So in the beginning I have text boxes in which you have to put the order number in so you can decided which copies you would like to print. I also have a enter button but the boss would like the textbox to be validated immediatly after the number is entered into the textbox so all the other information isn't entered for the wrong number. How do you validate numbers in a textbox without using the click event.

    Thank you for your time.

    Beau 
    Monday, July 14, 2008 3:11 PM

All replies

  • Hi,

    the Textbox Control has a 2 Methods called Validating and Validated. This would be the best
    approch. Just look in your VS Help. There is an Example, that explains everything
    Monday, July 14, 2008 3:49 PM
  • Would I have to do some kind of loop also? I have found like three examples of validation code but I can't get any of them to work.
    Monday, July 14, 2008 8:12 PM
  • Hi,

    the Validating Event is normaly fired, when the user leaves the Textbox. So if the Data is not right, just keep
    the Focus at the Textbox and maybe show the user the Error.
    Tuesday, July 15, 2008 8:03 AM
  • Hi Beau,

    as an alternative to the Validating event, you can also use the TextChanged event to call a function every time the text is changed inside the textbox.
    This has the advantage that you can already do something even if the user does not leave the textbox (while he is typing).
    But be careful with this event, because it will fire whenever a single key is pressed inside the textbox, so depending on how heavy your validation is, this might slow down the text input in your textbox!

    Cheers, Daniel
    Please mark the post as answer if solved and maybe post the final solution for others
    Tuesday, July 15, 2008 10:39 AM
  • I tried a few things and still encountered some errors. Would anyone possibly have any examples?
    Tuesday, July 15, 2008 2:34 PM
  • Hi Beau,

    it would be useful if you can post some code pointing out which errors occur and where, to have a pictures of what you are doing.
    Just posting random examples will not make sense at all...

    A+ Daniel
    Please mark the post as answer if solved and maybe post the final solution for others
    Tuesday, July 15, 2008 2:43 PM
  •  This is all of my code I have so far.  the text boxes that i have are right next to eachother with a dash in the middle. our sales order numbers are in the format of yy/mm-4digit order number. My goal is to get that to validate before i have to press my enter button to submit the order. So the first textbox needs to be between 0001-9912 and the second between 0-9999.

    Private Sub uiExitButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles uiExitButton.Click

    Me.Close()

    End Sub





    Private Sub uiEnterButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles uiEnterButton.Click

    Dim NumOfLabels As Integer

    Dim yearmonth, salesOrderNum As String



    yearmonth = Integer.Parse(Me.uiYearMonthTextBox.Text)

    salesOrderNum = Integer.Parse(Me.uiOrderNumTextBox.Text)

    NumOfLabels = Integer.Parse(Me.uiQTYTextBox.Text)



    If yearmonth.Length <> 4 Then

    MessageBox.Show("Must Be 4-Digits(Include Zeros)")

    Me.uiYearMonthTextBox.Focus()



    End If

    If salesOrderNum.Length <> 4 Then

    MessageBox.Show("Order Number Must be 4-Digits (Include Zeros)")





    End If

    If yearmonth > 9912 Then

    MessageBox.Show("Please Enter A Valid Number 0001-9912.", "Metso Shipping Solution", _

    MessageBoxButtons.OK, MessageBoxIcon.Information)



    End If



    If yearmonth.Length = uiYearMonthTextBox.MaxLength Then

    uiLabelGroupBox.Focus()

    End If





    Me.uiYearMonthTextBox.Text = ""

    Me.uiOrderNumTextBox.Text = ""

    Me.uiQTYTextBox.Text = ""

    Me.uiYesRadioButton.Checked = True

    Me.uiShowYesRadioButton.Checked = True

    Me.uiPackingNoRadioButton.Checked = True

    Me.uiBillNoRadioButton.Checked = True

    Me.uiShippingNoRadioButton.Checked = True

    'send focus to sales order

    Me.uiYearMonthTextBox.Focus()



    End Sub











    Private Sub uiClearButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles uiClearButton.Click





    Me.uiYearMonthTextBox.Text = ""

    Me.uiOrderNumTextBox.Text = ""

    Me.uiQTYTextBox.Text = ""

    Me.uiYesRadioButton.Checked = True

    Me.uiShowYesRadioButton.Checked = True

    Me.uiPackingNoRadioButton.Checked = True

    Me.uiBillNoRadioButton.Checked = True

    Me.uiShippingNoRadioButton.Checked = True

    'send focus to sales order

    Me.uiYearMonthTextBox.Focus()



    End Sub





    Private Sub uilabelGroupBox_Click(ByVal sender As Object, ByVal e As System.EventArgs) _

    Handles uiYesRadioButton.Click, uiNoRadioButton.Click

    If Me.uiYesRadioButton.Checked = True Then

    Me.uiQTYTextBox.Visible = True

    Else

    Me.uiQTYTextBox.Text = 0

    Me.uiShowYesRadioButton.Focus()



    End If



    End Sub





    Private Sub uiyearmonthtextbox_KeyPress(ByVal sender As System.Object, ByVal e As System.Windows.Forms.KeyPressEventArgs) _

    Handles uiYearMonthTextBox.KeyPress, uiOrderNumTextBox.KeyPress, uiQTYTextBox.KeyPress

    If Not Char.IsNumber(e.KeyChar) And Not Char.IsControl(e.KeyChar) Then

    e.Handled = True

    End If

    End Sub









    Private Sub CheckEntry(ByVal sender As Object, ByVal e As System.EventArgs) _

    Handles uiYearMonthTextBox.TextChanged, uiOrderNumTextBox.TextChanged, _

    uiQTYTextBox.TextChanged

    Dim TB As TextBox = CType(sender, TextBox)

    If TB.Text.Length = TB.MaxLength Then

    End If

    If TB.SelectionStart = 4 Then

    Me.SelectNextControl(TB, True, True, True, True)

    End If

    End Sub







    End Class

    Tuesday, July 15, 2008 3:30 PM
  •   Also one more thing. Does anyone know how after i get this working I can sync the application and the PDF files together so that when I do enter the right sales order number it knows which one to open ?
    Tuesday, July 15, 2008 3:55 PM
  • How about using 1 text box and a regular expression to ensure that it meets the requirements?  Here is an example validation sub:

    Private Sub TextBox1_Validating(ByVal sender As ObjectByVal e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating  
        If Not System.Text.RegularExpressions.Regex.Match(Me.TextBox1.Text, "\d\d[1-12]-\d\d\d\d").Success Then 
            e.Cancel = True 
        End If 
    End Sub 
     

    Now, I'm no regex pattern master by any means - so that may not be the best pattern string, but it should work.  It will check for:

    digit 0-9
    digit 0-9
    number 1-12
    hyphen
    digit 0-9
    digit 0-9
    digit 0-9
    digit 0-9

    That should follow your rules and not allow the user to leave the textbox until a proper sales order number is entered.
    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"
    Tuesday, July 15, 2008 5:13 PM
  • Reed,

    I tried that, and got rid of all the extras I had. But, when I ran the application it wouldnt let me out of the textbox at all nor would the exit button work any longer. Another question. With that code would you have to enter the dash or would it do it by itself?
    Tuesday, July 15, 2008 5:44 PM
  • I'm sorry, you do have to test to see if the textbox is empty and allow that if you want them to be able to leave the textbox while there is no value:

        Private Sub TextBox1_Validating(ByVal sender As ObjectByVal e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating  
            If Me.TextBox1.Text.Length > 0 Then 
                If Not System.Text.RegularExpressions.Regex.Match(Me.TextBox1.Text, "\d\d[1-12]-\d\d\d\d").Success Then 
                    e.Cancel = True 
                End If 
            End If 
        End Sub 

    Second, no, it would not automatically fill in a dash - the user would have to type it.  You could use a MaskedTextBox instead to force the dash to be added for you.

    Replace your TextBox with a MaskedTextBox and set this as the Mask:  0000-0000

    Then use code something like:

        Private Sub MaskedTextBox1_Validating(ByVal sender As ObjectByVal e As System.ComponentModel.CancelEventArgs) Handles MaskedTextBox1.Validating  
            Dim fmt As MaskFormat = Me.MaskedTextBox1.TextMaskFormat  
            Me.MaskedTextBox1.TextMaskFormat = MaskFormat.ExcludePromptAndLiterals  
            If Me.MaskedTextBox1.Text.Length > 0 Then 
                If Not System.Text.RegularExpressions.Regex.Match(Me.MaskedTextBox1.Text, "\d\d[1-12]-\d\d\d\d").Success Then 
                    e.Cancel = True 
                End If 
            End If 
            Me.MaskedTextBox1.TextMaskFormat = fmt  
        End Sub 

    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"
    Tuesday, July 15, 2008 6:15 PM
  • I looked for the Masked textbox in the customise toolbox and couldn't find it. Any ideas?

    Thanks
    Beau

    Tuesday, July 15, 2008 7:12 PM
  • Hi Beau,

    I did not get the regex running 100% correct, but I did not want to further play around with it... The masked textbox is new is framework 2.0, which means that you will not have it if you are still using framework 1.1 (Visual Studio 2003).
    To get the functionality you want, I used this piece of code:

        Private Sub txtOrder_TextChanged(ByVal sender As System.ObjectByVal e As System.EventArgs) Handles txtOrder.TextChanged  
            With txtOrder  
                If .Text.Length = 4 Then 
                    .Text += "-" 
                ElseIf .Text.Length > 9 Then 
                    .Text = Strings.Left(.Text, 9)  
                End If 
                .Select(.Text.Length, 0)  
            End With 
        End Sub 
     

    But this does not do the validation, just the mask.

    For the validation, I would still use Reed's regex approach, but add some functionality to allow the user to leave the the textbox if he want to cancel (eg by catching the Esc button), otherwise he is lost inside the textbox until he enters a correct number or deletes it completely.

    Cheers, Daniel
    Please mark the post as answer if solved and maybe post the final solution for others
    Wednesday, July 16, 2008 8:17 AM