How to validate Windows Form user input

05 Apr

Here are a couple notes taken from the MSDN User Input Validation in Windows Forms article.

Where to place the validation logic :
Validating event. If the Control.CausesValidation property is set to false, the Validating and Validated events of that control will not fire.

When does the validating event execute :
1. By Form.AutoValidate property. It specifies whether the control is validated on focus change by the AutoValidate enumerated value. (Implicit validation)
2. By calling Validate or ValidateChildren. (Explicit validation)

How to close the form when validation failed using AutoValidate :
There’s no problem closing the form if AutoValidate is set to Disable or EnableAllowFocusChange. If not, set e.Cancel to false in the Form.Closing event.

Below is a simple code sample for general validation purpose. The form checks if both TextBoxes are empty. The settings are as follows:
Form.AutoValidate: Disable or EnableAllowFocusChange
TextBox.CauseValidation: True

Private Sub ButtonSend_Click(ByVal sender As System.Object, _
                             ByVal e As System.EventArgs) _
                             Handles ButtonSend.Click
    'ValidateChildren() returns true when all child controls are validated
    If Me.ValidateChildren() Then
    End If
End Sub

Private Sub TextBoxNotEmpty_Validating( _
    ByVal sender As System.Object, _
    ByVal e As System.ComponentModel.CancelEventArgs) _
    Handles TextBoxPhone.Validating, TextBoxName.Validating

    If TypeOf sender Is TextBox Then
        Dim tb As TextBox = sender
        'Check if the TextBox is empty
        If String.IsNullOrEmpty(tb.Text.Trim()) Then
            'Show error message using ErrorProvider
            Me.ErrorProvider1.SetError(tb, "Error message")
            'Cancel the events of the sender after Validating event
            e.Cancel = True
            'Clear error message
            Me.ErrorProvider1.SetError(tb, String.Empty)
        End If
    End If
End Sub

Private Sub ValidationTest_FormClosing( _
    ByVal sender As System.Object, _
    ByVal e As System.Windows.Forms.FormClosingEventArgs) _
    Handles MyBase.FormClosing

    'Close the form without the need for validation when AutoValidate is on
    e.Cancel = False
End Sub
Leave a comment

Posted by on April 5, 2012 in .NET, VB, Winform



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: