Validation - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!



abc123456798789abc123456798789 abcPosts: 0Member
edited June 2014 in VB.NET

How to do validation in textbox in


  • jdforsythejdforsythe OhioPosts: 2Member
    edited July 2014

    Say you have a textbox

    Private Function isValidEmailAddress(ByVal emailAddress As String) As Boolean 
       ' Confirm there is text in the control. 
       If emailAddress.Length = 0 Then Return False 
       ' Confirm that there is an "@" and a "."
       ' Obviously this can be much better validation
       Dim atIndex As Integer = emailAddress.IndexOf("@")
       If atIndex > -1 Then 
          If (emailAddress.IndexOf(".", atIndex) > atIndex) Then Return True
       End If
       Return False 
    End Function
    Private Sub TextBox1_Validating(ByVal sender As Object, _
    ByVal e As System.ComponentModel.CancelEventArgs) Handles TextBox1.Validating
       If Not ValidEmailAddress(TextBox1.Text.Trim) Then 
          ' Cancel the event and select the text to be corrected by the user.
          e.Cancel = True
          TextBox1.Select(0, TextBox1.Text.Length)
          ' Set the ErrorProvider error with the text to display.  
          Me.ErrorProvider1.SetError(TextBox1, "You must enter a valid email address")
       End If 
    End Sub
    Private Sub TextBox1_Validated(ByVal sender As Object, _
    ByVal e As System.EventArgs) Handles TextBox1.Validated
       ' If all conditions have been met, clear the error provider of errors.
       ErrorProvider1.SetError(TextBox1, "")
    End Sub

    You may be interested in the order events fire on the TextBox:
    Enter, GotFocus, Leave, Validating, Validated, LostFocus
    Enter, GotFocus, LostFocus, Leave, Validating, Validated

    Using the ErrorProvider (just drag one onto your form from the toolbox) will greatly ease the displaying of errors. This automatically shows the user what to do (based on your message to the ErrorProvider). It will also disable all the other controls - but ONLY if they have CausesValidation=true. So even if you aren't going to validate a textbox, if you want it disabled when something else isn't valid, make sure you leave CausesValidation set to True (default).

Sign In or Register to comment.