Partager via


User Input Validation in Windows Forms

When users enter data into your application, you may want to verify that the data adheres to a certain format before your application uses it. You may require that certain text fields not be zero-length, that a field be formatted as a phone number or other type of well-formed data, or that a string not contain any unsafe characters that could be used to compromise the security of a database. Windows Forms provides several ways for you to verify the correctness of data at various moments in your application's lifetime.

Event-Driven Validation

If you want full programmatic control over validation, or need to perform complex validation checks, you should use the validation events built into most Windows Forms controls. Each control that accepts free-form user input has a Validating event that will occur whenever the control requires data validation.

The Validating event is supplied an object of type CancelEventArgs. If you determine that the control's data is not well-formatted, you can cancel the Validating event by setting this object's Cancel property to true. If you do not set the Cancel property, Windows Forms will assume that validation succeeded for that control, and fire the Validated event.

Implicit and Explicit Validation

This begs the question: When does a control's data get validated? This is up to you, the developer. You can use either implicit or explicit validation, depending upon the needs of your application.

If you want validation to occur whenever the user takes the input focus away from a control, you need to set that control's AutoValidate property to true. This is called implicit validation. In this scenario, if you cancel the Validating event, the behavior of the control will be determined by what value you assigned to AutoValidate. If you assigned EnablePreventFocusChange, canceling the event will cause the Validated event not to occur. Input focus will remain on the current control until the user changes the data to an appropriate format. If you assigned EnableAllowFocusChange, the Validated event will not occur when you cancel the event, but focus will still change to the new control.

Assigning Disable to the AutoValidate property prevents implicit validation altogether. To validate your controls, you will need to use explicit validation. This can be useful when you want to validate controls based on some user event, such as a button click, or when you want to validate an entire form at once instead of on a control-by-control basis. You can activate explicit validation by calling either Validate or ValidateChildren. The former will validate the last control to have lost focus, while the latter allows you to validate all child controls within a form or container control.

Default Implicit Validation Behavior for Windows Forms Controls

Different Windows Forms controls have different defaults for their AutoValidate property. Below is a table of the most common controls and their defaults.

  • Form
    EnableAllowFocusChange

Data Binding and Event-Driven Validation

Validation is very useful when you've bound your controls to a data source, such as a database table. Using validation, you can ensure that your control's data satisfies the format required by the data source, and that it doesn't contain any special characters such as quotation marks and back slashes that might be unsafe.

When you use data binding, the data in your control is synchronized with the data source during execution of the Validating event. If you cancel the Validating event, the data will not be synchronized with the data source.

Validation with the MaskedTextBox Control

If you need to force users to enter data in a well-defined format, such as a phone number or a part number, you can accomplish this quickly and with minimal code using the MaskedTextBox control. A "mask" is a string comprised of characters from a masking language that specifies which characters can be entered at any given position in the text box. The control displays a set of prompts to the user. If the user types an incorrect entry - attempts to enter a character, for example, when a digit is required - the control will automatically reject the input.

The masking language used by MaskedTextBox is very flexible, allowing you to specify required characters, optional characters, literal characters such as hyphens and parentheses, currency characters, and date separators. The control also works well when bound to a data source: the Format event on a data binding can be used to reformat incoming data to conform to the mask, and the Parse event used to reformat outgoing data to conform to the specifications of the data field.

For more information, see MaskedTextBox Control (Windows Forms).