I should first explain what I mean by "validation" when it comes to the basic controls. There are quite a few things you need to keep in mind when setting up fields in a form. Here are some considerations to make when you use TextBoxes and other free-form data entry controls:
Is the user allowed in this field?
Should the field be numeric or alpha, or both?
Is there a minimum length to the field?
Is there a maximum length to the field?
Should control characters be allowed?
Are there any other characters that are not allowed?
Should the field be validated on a character-by-character basis or when the user leaves the field?
Will there be multiple lines to this field?
Believe it or not, .NET provides controls that actually allow you to set up many of these parameters as control properties without your even writing any validation code. Let's look at some of the validation events. In the following sections, I outline some of the most commonly used controls.
Every visible control that can be written to can let you know when it is time to perform any validation. Two events are raised concerning validation:
Validating: This occurs when the control tells you it needs validation.
Validated: This occurs when the control thinks you are finished validating.
There is also a Boolean property called CausesValidation that, if set to false, suppresses these two events.
The validation events are considered focus events. The focus events occur when a control either gets the focus of attention on a form or loses it. These events occur in a certain order that lets you determine when you want to validate. The order is as follows:
Enter: The cursor has entered the control.
Focus: The control has gained focus of the keyboard and mouse.
Leave: The input focus is leaving the control.
Validating: The control is currently validating.
Validated: The control is done validating.
Lost Focus: The control has completely lost focus.
If you capture the Validating event, your delegate can either let the subsequent events go on or suppress them. You would suppress subsequent events if your validation code indicated a failure.
I cover validation events in more detail later in this chapter.