Home > Articles > Programming > ASP .NET

  • Print
  • + Share This
This chapter is from the book

ASP.NET Validation

ASP.NET Validation server controls allow you to easily validate any data a user has entered in a Web form. These controls support such validations as required fields and pattern matching, and they also make it easy to build your own custom validations. In addition, Validation controls allow you to completely customize the way error messages are displayed to users when data values don't pass validation.

Validation controls are similar to Web controls (see Day 5, "Beginning Web Forms"). They're created on the server, they output HTML to the browser, and they're declared with the same syntax:

<asp:ValidatorName runat="server"
 ControlToValidate="ControlName"
 ErrorMessage="Descriptive Text"/>

The difference is that these controls don't display anything unless the input fails validation. Otherwise, they're invisible and the user can't interact with them. Thus, a Validation control's job is to watch over another server control and validate its content. The ControlToValidate property specifies which user input server control should be watched. When the user enters data into the watched control, the Validator control checks the data to make sure it follows all the rules you've specified (see "How Validation Controls Work" later today).

Table 7.1 summarizes the types of predefined validation offered by ASP.NET. You'll use all of these controls as you progress through today's lesson. They all belong to the System.Web.UI.WebControls namespace.

Table 7.1 ASP.NET Validation Control Types

Validation Control

Description

RequiredFieldValidator

Ensures that the user doesn't skip a field that is required.

CompareValidator

Compares a user's entry against a constant value, against a property value of another control, or against a database value using a comparison operator (less than, equal to, greater than, and so on).

RangeValidator

Checks that a user's entry is between specified lower and upper boundaries. You can check ranges within pairs of numbers, alphabetic characters, and dates. Boundaries can be expressed as constants or as values derived from another control (from the .NET SDK documentation).

RegularExpressionValidator

Checks that the entry matches a pattern defined by a regular expression. This type of validation allows you to check for predictable sequences of characters, such as those in social security numbers, e-mail addresses, telephone numbers, postal codes, and so on (from the .NET SDK documentation).

CustomValidator

Checks the user's entry using validation logic that you code yourself. This type of validation allows you to check for values derived at runtime.


Unfortunately, Validation controls will only validate input with a subset of ASP.NET server controls. Most of the time, these controls will be more than enough to validate all user input. The controls that can have their input validated by ASP.NET's Validation controls are

  • HtmlInputText

  • HtmlTextArea

  • HtmlSelect

  • HtmlInputFile

  • TextBox

  • ListBox

  • DropDownList

  • RadioButtonList

Note that the Validation controls are supplements to the controls listed. They don't allow user input themselves.

How Validation Controls Work

To create a Validation control on an ASP.NET page, simply add the proper Validation control tag to your Web form. Each Validation control that you add has a specific job: watching over one other server control. When a user enters any information into that server control, its corresponding validator scrutinizes the input and determines if it passes the tests that you've specified. All this is accomplished without any intervention or extra code from the developer.

Validation controls work on both the client and server. When a user enters data into a Web control and it violates the validation rule you've specified, the user will be alerted immediately. In fact, ASP.NET won't allow a form to be posted that has invalid information! This means you don't have to send information back and forth from the server to provide validation—it occurs on the client side automatically. This provides a large boost in performance and a better experience for the users.

NOTE

Client-side validation only occurs on browsers that support DHTML and JavaScript.

When the form is finally posted to the server, ASP.NET validates the inputs again. This allows you to double-check the data against resources that may not have been available on the client-side, such as a database. You don't need to validate on the server again if you trust the client-side validation, but it can often help in situations that require more complex validation routines.

Although much of this functionality comes automatically, there are a lot of things that must be accomplished behind the scenes in order for these controls to work. Listing 7.3 is a simple example.

Listing 7.3 A Simple Validation Example

1: <%@ Page Language="VB" %>
2:
3: <script runat="server">
4:  sub Submit(obj as object, e as eventargs)
5:   if Page.IsValid then
6:    lblMessage.Text = "You passed validation!"
7:   end if
8:  end sub
9: </script>
10:
11: <html><body>
12:  <form runat="server">
13:   <asp:Label id="lblMessage" runat="server" /><p>
14:
15:   Enter your name:
16:   <asp:TextBox id="tbFName" runat="server" /><br>
17:   <asp:RequiredFieldValidator runat="server"
18:    ControlToValidate="tbFName"
19:    ErrorMessage="First name required"/><p>
20:
21:   <asp:Button id="tbSubmit" runat="server"
22:    Text="Submit"
23:    OnClick="Submit" />
24:  </form>
25: </body></html>

Save this file as listing0703.aspx and view it from your browser. Before looking at what goes on backstage, let's take a tour of the page itself.

In the HTML portion of the page, you see four server controls: Label (line 13), TextBox (line 16), RequiredFieldValidator Validation control (lines 17 through 19), and a Button control (lines 21 through 23). RequiredFieldValidator is declared just like any other control. It contains a control name and runat="server". The ControlToValidate property specifies which server control this validator should watch over (tbFName in this case).

If any data is entered into the tbFName text box, the RequiredFieldValidator is satisfied. This control only checks to see if a field contains data. Every Validation control has an IsValid property that indicates if the validation has passed. In this case, if the user enters any data, this property is set to true. Otherwise, it's false. When the form is posted, the Submit method on line 4 is executed. The Page.IsValid property makes sure all Validation controls on the page are satisfied. You could also check each individual control's IsValid property, but this way is faster. Lines 5–7 display a message to the user if all of the Validation controls in the page are satisfied with the user input.

Try clicking Submit without entering anything in the text box. You should see what's shown in Figure 7.2.

Figure 7.2 The Validation control displays an error message.

What happened? The Validation control on line 17 checks if its dependent control has any data in it. Since you didn't enter any information, the validator stops the form from posting and displays the message you specified in the ErrorMessage property on line 19. The server doesn't get to see the user input at all.

Try entering some information into the text box and moving out of the element. The error message disappears automatically! Erase the text, and the error message appears again. Each element is validated as soon as the focus leaves it.

NOTE

The dynamic appearance of the error message is only supported on browsers that support dynamic HTML (Internet Explorer and Netscape 4+).

Let's take a look at the HTML produced by your ASP.NET page. Right-click on the page and select view source. Listing 7.4 shows a portion of the HTML source.

Listing 7.4 The Condensed Source from Your Validation Page

1: ...
2:  <form name="ctrl1" method="post" action="listing0702.aspx"
3:   language="javascript" onsubmit="ValidatorOnSubmit();"
4:   id="ctrl1">
5: ...
6: ...
7:  <script language="javascript"
8:   src="/_aspx/1.0.2523/script/WebUIValidation.js">
9:  </script>
10: ...
11: ...
12:  <span id="ctrl6" controltovalidate="tbFName"
13:   errormessage="First name required" evaluationfunction=
14:   "RequiredFieldValidatorEvaluateIsValid" initialvalue=""
15:   style="color:Red;visibility:hidden;">
16:  First name required</span><p>
17: ...
18: ...
19:  <script language="javascript">
20:  <!--
21: ...
22: ...
23:   function ValidatorOnSubmit() {
24:    if (Page_ValidationActive) {
25:    ValidatorCommonOnSubmit();
26:    }
27:   }
28:  // -->
29:  </script>
30: ...
31: ...

This page has a lot of content, so let's just examine the important parts. On line 2, you see your standard form tag. However, notice that when this form is submitted (that is, when the Submit method is raised), the form executes the ValidatorOnSubmit function instead of posting directly to the server. This function, located on line 25, determines if validation is enabled for the page (which it is, by default) and executes another function that performs the validation processing (see "Disabling Validation" later today for more information).

On line 8, you see that your page includes a reference to the WebUIValidation.js JavaScript file, located on the server. This script, automatically generated by ASP.NET, contains all the necessary client-side DHTML functions to display dynamic error messages, validate the input, and post the data to the server. This file is quite large, so we won't examine it here—it's usually located at c:\inetpub\wwwroot\_aspx\version\script.

On line 12, you see the HTML output of the Validation server control—a <span> element. It contains a custom attribute, evaluationfunction, that tells WebUIValidation.js what type of validation to perform. Also, this span is set to "hidden," which means the user can't see it—that is, until the validator functions have their say.

This is a complicated process, but you don't have to build any of it because ASP.NET handles everything automatically.

When this client-side script executes and evaluates each Validation control on the page, it sets a parameter for each based on the outcome of the validation. These parameters are sent to the server for validation again. Figure 7.3 illustrates this process.

Figure 7.3 The validation process occurs on both server- and client-side.

NOTE

Recall that client-side validation only occurs on browsers that support DHTML. Additionally, if a client has JavaScript disabled, client-side validation won't occur.

Why does the server need to validate the information again? Suppose that you need to validate some of the information against a database that resides on the server. Or that you want to prevent a user from submitting a form more than once. Sometimes the extra validation might be necessary, and the added precaution can't hurt.

When the server receives the form data, it checks the state of each Validation control (through the IsValid property). If they've all been satisfied, ASP.NET sets the IsValid property for the Page object to true. Otherwise, it's set to false. Even if it's false, execution of your code will continue. The code will be executed whether or not the input was validated. Therefore, it's up to you to stop your code from executing if the data is invalid. This is usually done with a simple check to the Page.IsValid property.

  • + Share This
  • 🔖 Save To Your Account

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