Validation - Programmers Heaven

Howdy, Stranger!

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

Categories

Welcome to the new platform of Programmer's Heaven! We apologize for the inconvenience caused, if you visited us from a broken link of the previous version. The main reason to move to a new platform is to provide more effective and collaborative experience to you all. Please feel free to experience the new platform and use its exciting features. Contact us for any issue that you need to get clarified. We are more than happy to help you.

Validation

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

How to do validation in textbox in vb.net

Comments

  • jdforsythejdforsythe OhioPosts: 2Member
    edited July 15

    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: Keyboard: Enter, GotFocus, Leave, Validating, Validated, LostFocus Mouse: 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.