Home > Articles

Validating ASP.NET Pages

This chapter is from the book

Validating user input in ASP.NET Web forms is one of the most important tasks for developers. Users are very unpredictable when it comes to supplying information, so you must take extra precautions to make sure they give you the correct data. For example, suppose you ask a user for a credit card number. What happens if he enters non-valid input, such as dgffg934053? Or what if he leaves off one digit of the number? Obviously, this will cause some problems in your application, especially when he tries to place an order.

In ASP.NET, these types of validation are easy to perform. You have a bevy of options for validating user input, including pattern matching and making sure the input is within a given range. The Validation controls provide a number of methods to alert users about errors, and they can do so dynamically without requiring a post to the server. And when one of the built-in options doesn't meet your needs, you can build your own!

Today you're going to look at various ways to validate user input easily with ASP.NET. Specifically, you'll look at the Validation server controls, which make data entry validation easier than ever. You'll also look at examples of creating your own validation routines.

Today's lesson will cover the following:

  • Why and how to validate user input before ASP.NET

  • What ASP.NET Validation controls are and how they work

  • How to implement Validation controls in your pages

  • How to customize error messages displayed to the user

  • How to build custom Validation controls

Validation Scenarios

Imagine going to school to register for classes. The registrar asks you for your name. If you tell him that your name is "56," he's going to wonder if you're telling the truth. Most likely, he'll ask you for your name again. He must either verify that your name is indeed "56" or get your real name.

Any time that you ask people for information, you have to be prepared for the unexpected. You never know what they'll say when presented with a simple question. With computers, this kind of behavior can be disastrous. If an application is expecting one type of data, giving it another type of data may result in an error or even a crash (as you may have already experienced with your ASP.NET pages). Input validation is the process of making sure that the user provides the correct type of data.

Input validation is a must when you allow users to enter information manually into your ASP.NET pages. Most users will do their best to comply and enter the information you ask for in the proper format, but sometimes they make mistakes. Other users may like to try breaking applications by entering invalid information. In either case, getting data that you weren't expecting is a very common situation.

For example, imagine that you've created an e-commerce site that takes orders for office supplies. Eventually, you'll need to take personal information from the user, such as her name, e-mail, billing address, and so on. You must ensure that this information is accurate, or the order won't be processed correctly. For example, if the user enters a number for the shipping state, such as 45, and the application doesn't catch it immediately, the shipment may never be delivered and you'll end up with an irate customer.

So what happens if the user enters a number in place of her name? Or she enters a random string of characters for her e-mail address? Eventually, what you end up with is incorrect data being entered into your system. Detecting invalid input is vital for presenting a solid application.

Input validation also provides benefits for developers—specifically, coherent data. When you're designing your application, you should always be able to count on the data being in a specific format. For example, if you need to add two numbers, you need to make sure they are indeed numbers. Otherwise, the add operation won't work and your application will fail. When the input has been validated beforehand, you know that your add operation will succeed.

Let's examine a typical situation that requires user input validation. Listing 7.1 shows a simple user interface ASP.NET page that allows users to enter some personal information.

Listing 7.1 A Typical Scenario for Validation

1: <html><body>
2:  <form runat="server">
3:   <asp:Label id="lblHeader" runat="server"
4:    Height="25px" Width="100%" BackColor="#ddaa66"
5:    ForeColor="white" Font-Bold="true"
6:    Text="A Validation Example" />
7:   <asp:Label id="lblMessage" runat="server" /><br>
8:   <asp:Panel id="Panel1" runat="server">
9:    <table>
10:    <tr>
11:    <td width="100" valign="top">
12:     First and last name:
13:    </td>
14:    <td width="300" valign="top">
15:     <asp:TextBox id="tbFName" runat="server" />
16:     <asp:TextBox id="tbLName" runat="server" />
17:    </td>
18:    </tr>
19:    <tr>
20:    <td valign="top">Email:</td>
21:    <td valign="top">
22:     <asp:TextBox id="tbEmail"
23:      runat="server" />
24:    </td>
25:    </tr>
26:    <tr>
27:    <td valign="top">Address:</td>
28:    <td valign="top">
29:     <asp:TextBox id="tbAddress"
30:      runat="server" />
31:    </td>
32:    </tr>
33:    <tr>
34:    <td valign="top">City, State, ZIP:</td>
35:    <td valign="top">
36:     <asp:TextBox id="tbCity"
37:      runat="server" />,
38:     <asp:TextBox id="tbState" runat="server"
39:      size=2 />&nbsp;
40:     <asp:TextBox id="tbZIP" runat="server"
41:      size=5 />
42:    </td>
43:    </tr>
44:    <tr>
45:    <td valign="top">Phone:</td>
46:    <td valign="top">
47:     <asp:TextBox id="tbPhone" runat="server"
48:      size=11 /><p>
49:    </td>
50:    </tr>
51:    <tr>
52:    <td colspan="2" valign="top" align="right">
53:     <asp:Button id="btSubmit" runat="server"
54:      text="Add" />
55:    </td>
56:    </tr>
57:    </table>
58:   </asp:Panel>
59:  </form>
60: </body></html>

This listing uses a few Web controls to display a user interface. The user interface prompts the user for first and last name, e-mail address, street address, city, state, ZIP code, and phone number. The result of Listing 7.1 is shown in Figure 7.1.

Once the form is submitted, you have to verify that each field contains a valid entry before entering the data in a database. A common way to do this is through a series of if statements, as shown in Listing 7.2. This series of if statements validates all of the server controls in Listing 7.1.

Listing 7.2 Validating User Input from Listing 7.1 Through if Statements

1: <script runat="server">
2:  sub Submit(obj as Object, e as EventArgs)
3:   if tbFName.Text <> "" and not IsNumeric(tbFName.Text) then
4:    if tbLName.Text <> "" and not IsNumeric(tbLName.Text) then
5:    if tbAddress.Text <> "" then
6:     if tbCity.Text <> "" and not IsNumeric(tbCity.Text) then
7:      if tbState.Text <> "" and not IsNumeric(tbState.Text) then
8:       if tbZIP.Text <> "" and IsNumeric(tbZIP.Text) then
9:       if tbPhone.Text <> "" then
10:        lblMessage.Text = "Success!"
11:       else
12:        lblMessage.Text = "Phone is incorrect!"
13:       end if
14:       else
15:       lblMessage.Text = "ZIP is incorrect!"
16:       end if
17:      else
18:       lblMessage.Text = "State is incorrect!"
19:      end if
20:     else
21:      lblMessage.Text = "City is incorrect!"
22:     end if
23:    else
24:     lblMessage.Text = "Address is incorrect!"
25:    end if
26:    else
27:    lblMessage.Text = "Last name is incorrect!"
28:    end if
29:   else
30:    lblMessage.Text = "First name is incorrect!"
31:   end if
32:  end sub
33: </script>

As you can see, validating all of the controls in this manner is rather long and tedious. The if statement on line 3 verfies that the user has filled in the first name field, and also that the supplied data is not a number. The second if statement on line 4 does the same for the last name field. You proceed this way until you've checked every control that contains user input. Don't forget the else statements, which display a message telling the user what the error is.

After checking all of the user inputs in this fashion, you can take one of two courses. If all of the information entered by the user is in the correct format, you can insert the data in the data source. If any of the information is formatted improperly, you need to alert the user to the errors in the input (done with the else statements) and allow her to fix them before inserting the results into the data store (by simply redisplaying the page).

Figure 7.1 A typical user-entry page.

However, this can get quite complex because you often have to check for multiple cases on each input. For example, for the first name, you have to check that the field isn't blank, doesn't contain any numbers, doesn't contain spaces, and so on. This makes for a lot of if statements. As tedious as this may be, it's a typical method of validating user input. The process boils down to the following steps:

  1. Display the form to the user and allow her to enter data.

  2. Upon form submission, use if statements to check every user input. This includes checking for blank entries, the proper format and data type, valid ranges of information (for dates), and so on.

  3. If all if statements pass, perform your functionality.

  4. If it fails, redisplay the form, preferably with the fields prefilled with the previously entered user input. This allows the user to correct only the incorrect fields and leave the correct ones. Start over at step 2.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT 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 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 InformIT. 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.informit.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