Home > Articles > Microsoft > Other Microsoft

This chapter is from the book

Validating User Input

In order to make your application as robust as possible, the best solution to invalid or incorrect user input is to prevent the entry of "bad" data as often as possible. Validating user input before it is evaluated provides a better solution than complex exception-handling code that may add a great deal of resource overhead to your program. Here are the four basic techniques used to validate user input:

  • Restricting the available values by using the proper type of control, configured with a specific list of allowed values. Controls such as RadioButtons, ListBoxes, ComboBoxes, and CheckBoxes are often used for this type of validation. Configuring the properties of the controls allows for additional restriction of user input, such as controlling the case or length of text box input.

  • Restricting data entry through controls by enabling or disabling them based on the state of other controls. As an example of this technique, a set of controls allowing for the entry of address information might remain disabled until a valid customer ID has been selected in another control.

  • Capturing and evaluating user keystrokes and allowing only acceptable values to be recognized. This might be used to prevent the entry of symbols or alphabetic characters within a control that should hold only numeric characters.

  • Evaluating a control's data as a whole and warning the user of incorrect or unacceptable values. This is often used to warn a user when attempting to change focus from the control or close the form.

Control-Based Validation

You can restrict the allowable values within a control by using the properties that we discussed in Chapter 2, "Controls on Forms." In addition to simply restricting input to a selection from a list of values, configuration of control properties may be used in order to further limit possible input values. Of note are the CharacterCasing and MaxLength properties used in text-input controls such as the TextBox control.

CharacterCasing

The CharacterCasing property of a TextBox control may be used to force all input alphabetic characters to a particular case. The options for the CharacterCasing property are Normal (the default, which does not change the case of input characters), Upper (which forces all input to uppercase), and Lower (which forces all input to lowercase).

MaxLength

The MaxLength property of a TextBox or ComboBox control is used to restrict the maximum number of characters the user can input into the control. A value of zero (the default) specifies no specific limit to the number of characters that may be input by the user. This property does not restrict the length of values that may be input programmatically.

Control-Access Restriction

Manipulating access properties such as the Enabled and ReadOnly properties can be used to restrict data entry access within a control. When a control's Enabled value is set to False, it cannot receive focus. If the ReadOnly property of a TextBox control is set to True, it may still receive focus, allowing users to scroll through its contents while preventing changes.

Keystroke-Level Validation

When a user presses a key, three events are fired in order:

  1. KeyDown

  2. KeyPress

  3. KeyUp

The KeyPress event may be used in order to intercept input keyboard characters and perform validation tasks through the use of the KeyPressEventArgs class before the KeyUp event is handled. Table 3.4 details some important properties of the KeyPressEventArgs class.

Table 3.4 Important Properties of the KeyPressEventArgs Class

Property

Description

Handled

Indicates whether the event has been handled.

KeyChar

The character value corresponding to the pressed key.


The KeyPress event only fires for keys that generate character values, excluding function, control, and cursor-movement keys. To respond to the excluded keys, you must use the KeyDown and KeyUp events instead. These use the properties of the KeyEventArgs class, detailed in Table 3.5.

Table 3.5 Important Properties of the KeyEventArgs Class

Property

Description

Alt

True if the Alt key is pressed; otherwise False.

Control

True if the Ctrl key is pressed; otherwise False.

Handled

Indicates whether the event has been handled.

KeyCode

The keyboard code for the event. Its value is one of the values specified in the Keys enumeration.

KeyData

The key code for the pressed key, along with modifier flags that indicate the combination of Ctrl, Shift, and Alt keys that were pressed at the same time.

KeyValue

An integer representation of the KeyData property.

Modifiers

Modifier flags that indicate which combination of modifier keys (Ctrl, Shift, and Alt) were pressed.

Shift

True if the Shift key is pressed; otherwise, False.


NOTE

By default, only the control with the focus will respond to the KeyDown, KeyPress, and KeyUp events. If you set the KeyPreview property of a form to True, then the form will handle the same three events before the control with the focus handles them, thus allowing two tiers of keystroke-level validation.

Field-Level Validation

Validation may also be performed to include the entire value entered within a control by configuring validation code to run before focus is lost or the form is closed. When a user enters or leaves a field, the following events occur in order:

  1. Enter (the focus is about to enter the control)

  2. GotFocus (the focus has entered the control)

  3. Leave (the focus is about to leave the control)

  4. Validating (the data in the control is ready to validate)

  5. Validated (the data has been validated)

  6. LostFocus (the focus has left the control)

Of these events, the Validating event is most important for validating user input. That's because code within this event can halt the chain of events and prevent the user from moving on until any error is corrected.

The Validating Event

The Validating event is ideal for input value validation, as you may write code to check the value presented and display an error message to the user, or prevent the loss of focus from the current control until the value has been corrected.

The Focus method of the control may be used in order to redirect focus back to the same control programmatically, and the Cancel property of the CancelEventArgs object may be set to True, preventing the transfer of focus away from the current control.

TIP

Closing a form fires the Validating event. If you set the Cancel property to True during a Validating event when the form is being closed, this will prevent the form from closing. You can use the Closing event of the form to determine whether the form is closing and disable validation in this case, if you like.

The Validated event occurs after validation has occurred and may be used to perform actions based on the validated values, such as enabling or disabling other controls, as discussed previously in this section.

The CausesValidation Property

When using the Validating event to retain the focus in a control until a valid input value is received, you may prevent the user from being able to obtain help on what constitutes a valid input value by clicking another control such as the Help button in the toolbar. This is a result of the default setting (True) of the CausesValidation property of the Button control.

If you set the CausesValidation property of the Help Button control to False, the control may act without first triggering the Validating event in the control with current focus.

The ErrorProvider Component

The ErrorProvider component provided within the Visual Studio .NET toolbox allows for the display of error-validation messages using a small icon that includes a message that appears as a ToolTip when the user hovers his or her cursor over the displayed icon. Table 3.6 details the more important members of the ErrorProvider class.

Table 3.6 Important Members of the ErrorProvider Class

Member

Type

Description

BlinkRate

Property

Specifies the rate at which the error icon flashes.

BlinkStyle

Property

Specifies a value indicating when the error icon flashes.

ContainerControl

Property

Specifies the parent control of the ErrorProvider control.

GetError

Method

Returns the error description string for the specified control.

Icon

Property

Specifies an icon to display next to the parent control. The icon is displayed only when an error description string (SetError) has been set for the parent control.

SetError

Method

Sets the error description string for the specified control.

SetIconAlignment

Method

The location at which to place an error icon with respect to the control.

SetIconPadding

Method

The amount of extra space to leave between the specified control and its error icon.


Use of this component has many advantages over opening separate MessageBox components for each possible error, which may confuse users and complicate the desktop. The ErrorProvider component provides a simple user-friendly display that rapidly draws a user's attention to the control failing input validation. Figure 3.2 shows a form including an ErrorProvider component.

Figure 3.2Figure 3.2 A form displaying an example of the ErrorProvider component.

You may be tempted to omit validation from your applications. After all, if the user does exactly what you expect, your validation code will never be invoked. But generally speaking, this is a false economy. Users will find many ways to enter data that you never dreamed of. Validation code provides you with a way to correct problems immediately, and it can cut down on costly customer support.

Pearson IT Certification Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Pearson IT Certification and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Pearson IT Certification products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.pearsonitcertification.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020