Home > Articles > Microsoft > Other Microsoft

This chapter is from the book

User Input Validation

Validate user input.

It's a truism of the computer world that garbage-in is garbage-out. When designing an application that interacts with the user to accept data, you must ensure that the entered data is acceptable to the application. The most obvious time to ensure the validity of data is at the time of data entry itself. You can use various techniques for validating data, including these:

  • Restrict the values that a field can accept by using standard controls like combo boxes, list boxes, radio buttons and check boxes. These allow users to select from a set of given values rather than permitting free keyboard entry.

  • Capture the user's keystrokes and analyze them for validity. Some fields might require the user to enter only alphabetic values but no numeric values or special characters; in that case, you can accept the keystrokes for alphabetic characters while rejecting others.

  • Restrict entry in some data fields by enabling or disabling them depending on the state of other fields.

  • Analyze the contents of the data field as a whole and warn the user of any incorrect values when the user attempts to leave the field or close the window.

You saw how to use the various controls to limit input in Chapter 2, "Controls." I'll cover the rest of the techniques in this section.

Keystroke-Level Validation

When you press a key on a control, three events take place in the following order:

  1. KeyDown

  2. KeyPress

  3. KeyUp

You can add code to the event handlers for these events to perform keystroke-level validation. You will choose which event to handle based on the order in which the events are fired and the information passed in the event argument of the event handler.

The KeyPress event happens after the KeyDown event but before the KeyUp event. Its event handler receives an argument of type KeyPressEventArgs. Table 3.4 lists the properties of the KeyPressEventArgs class.

Table 3.4 Important Properties of the KeyPressEventArgs Class




Setting this property to True indicates that the event has been handled.


Gets the character value corresponding to the key.

The KeyPress event only fires if the key pressed generates a character value. This means you won't get a KeyPress event from keys such as function keys, control keys, and the cursor movement keys; you must use the KeyDown and KeyUp events to trap those keys.

The KeyDown and KeyUp events occur when a user presses and releases a key on the keyboard. The event handlers of these events receive an argument of the KeyEventArgs type; this argument provides the properties listed in Table 3.5.

Table 3.5 Important Properties of the KeyEventArgs Class




Returns True if Alt key is pressed, otherwise False.


Returns True if Ctrl key is pressed, otherwise False.


Indicates whether the event has been handled.


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


Gets 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.


Gets an integer representation of the KeyData property.


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


Returns True if Shift key is pressed, otherwise False.

The KeyPreview Property

By default, only the active control will receive keystroke events. The Form object also has KeyPress, KeyUp, and KeyDown events, but they are fired only when all the controls on the form are either hidden or disabled. However, you can modify this behavior.

When you set the KeyPreview property of a form to True, the form will receive all three events (KeyDown, KeyPress, and KeyUp) just before the active control receives them. This allows you to set up a two-tier validation on controls. If you want to discard a certain type of characters at the form level itself, you can set the Handled property for the event argument to True (This will not allow the event to propagate to the active control.); otherwise, the events will propagate to the active control. You can then use keystroke events at the control level to perform field-specific validation such as restricting the field to only numeric digits.

Field-Level Validation

Field-level validation ensures that the value entered in the field as a whole is in accordance with the application's requirement. If it isn't, you can alert the user to the problem. Appropriate times to perform field-level validations are

  • When the user attempts to leave the field.

  • When the content of the field changes for any reason. This isn't always a feasible strategy. For example, if you're validating a date to be formatted as "mm/dd/yy", it won't be in that format until all the keystrokes are entered.

When a user enters and leaves a field, events occur in the following order:

  1. Enter

  2. GotFocus

  3. Leave

  4. Validating

  5. Validated

  6. LostFocus

The Validating Event

The Validating event is the ideal place for performing field-level validation logic on a control. The event handler for the Validating event receives an argument of type CancelEventArgs. Its only property is the Cancel property. When set to True, this property cancels the event.

Inside the Validating event, you can write code to

  • Programmatically correct any errors or omissions made by the user.

  • Show error messages and alerts to the user so that he can fix the problem.

Inside the Validating event, you might also want to retain the focus in the current control, thus forcing user to fix the problem before proceeding further. You can use either of the following techniques to do this:

  • Use the Focus method of the control to transfer the focus back to the field.

  • Set the Cancel property of the CancelEventArgs object to True. This will cancel the Validating event, leaving the focus in the control.

A related event is the Validated event. The Validated event is fired just after the Validating event and enables you to take actions after the control's contents have been validated.

The CausesValidation Property

When you use the Validating event to retain the focus in a control by canceling the event, you must also consider that you are making your control sticky.

Consider what can happen if you force the user to remain in a control until the contents of that control are successfully validated. Now when the user clicks on the Help button in the toolbar to see what is wrong, nothing will happen unless the user makes a correct entry. This can be an annoying situation for users and one that you want to avoid in your application.


Validating Event and Sticky Forms The Validating event also fires when you close a form. If you set the Cancel property of the CancelEventArgs object to True inside this event, it will cancel the close operation as well.

This problem has a work-around: Inside the Validating event you should set the Cancel property of CancelEventArgs argument to True only if the mouse pointer is in the form's Client area. The close box is in the title bar outside the client Area of form. Therefore, when the user clicks the close box, the Cancel property will not be set to True.

The CausesValidation property comes to your rescue here. The default value of the CausesValidation property for any control is True, meaning that the Validating event will fire for any control requiring validation before the control in question receives focus.

When you want a control to respond irrespective of the validation status of other controls, set the CausesValidation property of that control to False. So in the previous example, the Help button in the toolbar should have its CausesValidation property set to False.


The ErrorProvider component in the Visual Studio .Net toolbox is useful when showing validation-related error messages to the user. The ErrorProvider component can display a small icon next to a field when the field contains an error. When the user hovers the mouse pointer over the icon, it also displays an error message as a ToolTip. This is a better way of displaying error messages as compared to the old way of using message boxes because it eliminates at least two serious problems with message boxes:

  • If you have errors in multiple controls, several message boxes popping up simultaneously can annoy or scare users.

  • After the user dismisses a message box, the error message is no longer available for reference.

Table 3.6 lists some important members of the ErrorProvider class that you should be familiar with.

Table 3.6 Important Members of the ErrorProvider Class






Specifies the rate at which the error icon flashes.



Specifies a value indicating when the error icon flashes.



Specifies the parent control of the ErrorProvider control.



Returns the error description string for the specified control.



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



Sets the error description string for the specified control.



Sets the location to place an error icon with respect to the control. It has one of the ErrorIconAlignment values.



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

The ErrorProvider object displays an error icon next to a field when you set the error message string. The error message string is set by the SetError method. If the error message is empty, no error icon is displayed and the field is considered to be correct. You'll see how to use the ErrorProvider component in Step By Step 3.6.

STEP BY STEP 3.6 Using the ErrorProvider Control and Other Validation Techniques

  1. Add a new Windows Form to your Visual Basic .NET project.

  2. Place three TextBox controls (txtMiles, txtGallons, and txtEfficiency) and a Button (btnCalculate) on the form's surface and arrange them as was shown in Figure 3.1. Add the label controls as necessary.

  3. Add an ErrorProvider (ErrorProvider1) control to the form. The ErrorProvider control will be displayed in the component tray.

  4. Double-click the form and add the following code to handle the form's Load event:

    Private Sub StepByStep3_6_Load( _
     ByVal sender As System.Object, _
     ByVal e As System.EventArgs) Handles MyBase.Load
      ' Set the ErrorProvider's Icon 
      ' alignment for the textbox controls
      ErrorProvider1.SetIconAlignment( _
       txtMiles, ErrorIconAlignment.MiddleLeft)
      ErrorProvider1.SetIconAlignment( _
       txtGallons, ErrorIconAlignment.MiddleLeft)

    End Sub

  5. Add code to handle the Validating events of the txtMiles and txtGallons controls:

    Private Sub txtMiles_Validating(ByVal sender As Object, _
     ByVal e As System.ComponentModel.CancelEventArgs) _
     Handles txtMiles.Validating
        Dim decMiles As Decimal = _
        ErrorProvider1.SetError(txtMiles, "")
      Catch ex As Exception
        ErrorProvider1.SetError(txtMiles, ex.Message)
      End Try
    End Sub
    Private Sub txtGallons_Validating(ByVal sender As Object, _
     ByVal e As System.ComponentModel.CancelEventArgs) _
     Handles txtGallons.Validating
        Dim decGallons As Decimal = _
        If (decGallons > 0) Then
          ErrorProvider1.SetError(txtGallons, "")
          ErrorProvider1.SetError(txtGallons, _
           "Please enter a positive non-zero value")
        End If
      Catch ex As Exception
        ErrorProvider1.SetError(txtGallons, ex.Message)
      End Try

    End Sub

  6. Add the following code to the Click event handler of btnCalculate:

    Private Sub btnCalculate_Click( _
     ByVal sender As System.Object, _
     ByVal e As System.EventArgs) Handles btnCalculate.Click
      ' Check whether the error description is not empty 
      'for either of the textbox controls 
      If (ErrorProvider1.GetError(txtMiles) <> "") Or _
       (ErrorProvider1.GetError(txtGallons) <> "") Then
        Exit Sub
      End If
        Dim decMiles As Decimal = _
        Dim decGallons As Decimal = _
        Dim decEfficiency As Decimal = decMiles / decGallons
        txtEfficiency.Text = _
         String.Format("{0:n}", decEfficiency)
      Catch ex As Exception
        Dim msg As String = _
         String.Format("Message: {0}" & vbCrLf & _
         "Stack Trace:" & vbCrLf & "{1}", _
         ex.Message, ex.StackTrace)
        MessageBox.Show(msg, ex.GetType().ToString())
      End Try

    End Sub

  7. Set the form as the startup object for the project.

  8. Run the project. Enter values for miles and gallons and run the program. It will calculate the mileage efficiency as expected. You will notice that when you enter an invalid value into any of the TextBox controls, the error icon starts blinking. It will display an error message when the mouse is hovered over the error icon, as shown in Figure 3.11.

Figure 3.11 ErrorProvider control showing the error icon and the error message.

Enabling Controls Based On Input

One of the useful techniques for restricting user input is the selective enabling and disabling of controls. Some common cases in which this is useful are

  • Your application might have a Check Here If You Want to Ship to a Different Location check box. When the user checks the check box, you should allow her to enter values in the fields for a shipping address. Otherwise, the shipping address is same as the billing address.

  • In a Find dialog box, you have two buttons labeled Find and Cancel. You want to keep the Find button disabled initially and enable it only when the user enters some search text in the text box.

The Enabled property for a control is True by default. When you set it to False, the control cannot receive the focus and will appear grayed out.

For some controls, such as the TextBox, you can also use the ReadOnly property to restrict user input. One advantage of using the ReadOnly property is that the control will still be able to receive focus so that users will be able to scroll through the text in the control if it is not completely visible. In addition, users can also select and copy the text to the clipboard if the ReadOnly property is true.

Other Properties for Validation

In addition to already mentioned techniques, the CharacterCasing and MaxLength properties allow you to enforce some restrictions on the user input.

The CharacterCasing Property

The CharacterCasing property of a TextBox control changes the case of characters in the text box as required by your application. For example, you might want to convert all characters entered in a text box used for entering a password to lowercase to avoid case confusion.

This property can be set to CharacterCasing.Lower, CharacterCasing.Normal (the default value) or CharacterCasing.Upper.

The MaxLength Property

The MaxLength property of a TextBox or a ComboBox specifies the maximum number of characters the user can enter into the control. This property comes in handy when you want to restrict the size of some fields such as a telephone number or a ZIP code.


MaxLength The MaxLength property only affects the text entered into the control interactively by the user. Programmatically, you can set the value of the Text property to a value that is larger than the value specified by the MaxLength property. So you can use the MaxLength property to limit user input without limiting the text that you can programmatically display in the control.

When the MaxLength property is zero (the default), the number of characters that can be entered is limited only by the available memory. In practical terms, this means that the number of characters is generally unlimited.

In Guided Practice Exercise 3.2 you will learn to use some of the validation tools such as the Enabled property, the Focus method of the TextBox control, and the ErrorProvider control.


In this exercise, your job is to add some features to the keyword searching application you created in Guided Practice Exercise 3.1. The Keyword text box and the Search button should be disabled when the application is launched. These controls should be enabled as the user progresses through the application. The application assumes that the entered keyword must be a single word. If it is not, you must display an error icon and set the error message. The keyword control should not lose focus unless the user enters valid data in the text box.

Try this on your own first. If you get stuck, or would like to see one possible solution, follow these steps:

  1. Add a new form to your Visual Basic .NET Project.

  2. Place three Label controls, two TextBox controls, and two Button controls on the form, arranged as was shown in Figure 3.8. Name the text box for accepting file names txtFileName and the Browse button btnBrowse. Name the text box for accepting keywords txtKeyword and the search button btnSearch. Name the results label lblResult.

  3. Add an OpenFileDialog control to the form and change its name to dlgOpenFile. Add an ErrorProvider (ErrorProvider1) control to the form. The ErrorProvider control will be placed in the component tray.

  4. Double-click the form and add the following code to handle the Form's Load event:

    Private Sub GuidedPracticeExercise3_2_Load( _
     ByVal sender As System.Object, _
     ByVal e As System.EventArgs) Handles MyBase.Load
      ' Disable the Keyword textbox and Search button
      txtKeyword.Enabled = False
      btnSearch.Enabled = False
      ErrorProvider1.SetIconAlignment( _
       txtKeyword, ErrorIconAlignment.MiddleLeft)
    End Sub
  5. Attach TextChanged and Validating event handlers to the txtKeyword control by adding the following code:

    Private Sub txtKeyword_TextChanged(ByVal sender As Object, _
     ByVal e As System.EventArgs) Handles txtKeyword.TextChanged
      If txtKeyword.Text.Length = 0 Then
        btnSearch.Enabled = False
        btnSearch.Enabled = True
      End If
    End Sub
    Private Sub txtKeyword_Validating(ByVal sender As Object, _
     ByVal e As System.ComponentModel.CancelEventArgs) _
     Handles txtKeyword.Validating
      If txtKeyword.Text.Trim().IndexOf(" ") >= 0 Then
        ErrorProvider1.SetError(txtKeyword, _
         "You may only search with a single word")
        txtKeyword.Select(0, txtKeyword.Text.Length)
        ErrorProvider1.SetError(txtKeyword, "")
      End If
    End Sub
  6. Create a method named GetKeywordFrequency that accepts a string and returns the number of lines containing it. Add the following code to the method:

    Private Function GetKeywordFrequency( _
     ByVal strPath As String) As Integer
      Dim count As Integer = 0
      If File.Exists(strPath) Then
        Dim sr As StreamReader = _
         New StreamReader(txtFileName.Text)
        Do While (sr.Peek() > -1)
          If sr.ReadLine().IndexOf( _
           txtKeyword.Text) >= 0 Then
            count += 1
          End If
      End If
      GetKeywordFrequency = count
    End Function
  7. Add the following code to the Click event handler of the btnBrowse button:

    Private Sub btnBrowse_Click(ByVal sender As System.Object, _
     ByVal e As System.EventArgs) Handles btnBrowse.Click
      If dlgOpenFile.ShowDialog() = DialogResult.OK Then
        txtFileName.Text = dlgOpenFile.FileName
        txtKeyword.Enabled = True
      End If
    End Sub
  8. Add the following code to the Click event handler of the btnSearch button:

    Private Sub btnSearch_Click(ByVal sender As System.Object, _
     ByVal e As System.EventArgs) Handles btnSearch.Click
      If ErrorProvider1.GetError(txtKeyword) <> "" Then
        Exit Sub
      End If
      lblResult.Text = String.Format( _
       "The keyword: '{0}', found in {1} lines", _
       txtKeyword.Text, _
      Catch ex As Exception
        Dim msg As string = _
         String.Format("Message:" & vbCrLf & "{0}" & _
         vbCrLf & vbCrLf & "StackTrace:" & vbCrLf & "{1}", _
         ex.Message, ex.StackTrace)
        MessageBox.Show(msg, ex.GetType().ToString())
      End Try
    End Sub
  9. Set the form as the startup object for the project.

  10. Run the project. Note that the Keyword text box and the Search button are disabled. Click the Browse button and select an existing file to enable the Keyword text box. Enter the keyword to search in the file to enable the Search button. Click the Search button. If the keyword entered is in wrong format (if it contains a space), the ErrorProvider control will show the error message and the icon.

  • It is generally a good practice to validate user input at the time of data entry. Thoroughly validated data will result in consistent and correct data stored by the application.

  • When a user presses a key three events are generated: KeyDown, KeyPress, and KeyUp in that order.

  • The Validating event is the ideal place for storing the field-level validation logic for a control.

  • The CausesValidation property specifies whether validation should be performed. If False, the Validating and Validated events are suppressed.

  • The ErrorProvider component in the Visual Studio .Net toolbox shows validation-related error messages to the user.

  • A control cannot receive the focus and appears grayed out if its Enabled property is set to False.

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.


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.


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.


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.


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


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


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.


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.


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