Home > Articles > Programming > ASP .NET

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

Customizing Validation

Validation controls are highly customizable. You can manipulate the way error messages are displayed, decide how users are alerted about errors, and even create custom Validation controls. ASP.NET gives developers a rich set of capabilities.

Error Messages

The examples you've been developing today all place the Validation controls immediately after the controls to validate. This isn't a requirement—Validation controls can be located anywhere on the page. You can place them all at the top of the page if you want to group error messages, for instance.

Let's take a look at Figure 7.4 again. There's a lot of white space between the UI elements on the page because of your Validation controls. Even though the validators may not display any message, they still take up space. You can remove the <br> after each control to eliminate the white space, but then the error messages are still placed as if something were in the way, as shown in Figure 7.6. This type of display is called static. You can easily combat this, however, by allowing dynamic display. Simply set the Display property to Dynamic. For example, the following code shows the first name and last name fields RequireFieldValidators as dynamically displayed objects:

<asp:RequiredFieldValidator runat="server" 
 ControlToValidate="tbFName" 
 ErrorMessage="First name required"
 Display="dynamic"/>
<asp:RequiredFieldValidator runat="server" 
 ControlToValidate="tbLName" 
 ErrorMessage="Last name required"
 Display="dynamic"/>
<asp:CompareValidator runat="server"
 ControlToValidate="tbFName"
 ControlToCompare="tbLName"
 Type="String"
 Operator="NotEqual"
 ErrorMessage="First and last name cannot be the same"
 Display="dynamic" />

The only addition is the Display="dyanamic" property. Adding this property to all of the controls in Listing 7.4 produces Figure 7.7.

Figure 7.6 The error message seems out-of-place because other Validation controls are in the way.

The white space problem is now eliminated. As the controls are validated, the page layout changes to make room for the error messages.

Figure 7.7 Dynamic display eliminates the white space problem.

CAUTION

This method may cause some unexpected changes in the page layout, so don't use it if you depend on a certain look, or until you've completely tested the new layouts.

Also, the Dynamic property is only supported by browsers that support the visible CSS style attribute (IE 5+ and Netscape 4+). This attribute can be used to selectively hide UI elements from the user.

Displaying Validation Summaries

So far, all of these examples have placed the error messages directly next to the server controls that are being validated. (Technically, the error messages are placed where the Validation control is located in the page.) This is very useful for telling users which controls have errors, especially with client-side validation. However, this isn't always the best place for error messages. You have a choice of where you place them:

  • In-line—In the same place where the Validation control is located in the page layout.

  • Summary—In a separate summary (can be a pop-up window on DHTML-capable browsers).

  • Both in-line and summary—The respective error messages can be different.

  • Customized.

The summary method is useful when you want to list all of the error messages in one location, such as at the top of the page. Depending on your application, users may prefer this method over an in-line display.

Rather than simply placing all of your Validation controls in one location, you can leave them where they are and use the ValidationSummary control. This control displays error messages with a specified format in a single location on the page. For example, add the following code near the top of Listing 7.5:

1: <asp:ValidationSummary runat="server"
2:  DisplayMode="BulletList" />

After filling out the form information and clicking the Submit button, you should see what's shown in Figure 7.8.

Figure 7.8 Displaying error message summaries.

This control is a bit different from the other Validation controls. It doesn't use the ControlToValidate or ErrorMessage properties. Rather, it takes the error messages from all the other controls in the page and displays them in one place. DisplayMode can be used to display the messages in a bulleted list (by specifying BulletList, as shown on line 2), or in paragraph format (with SingleParagraph).

The messages displayed in the ValidationSummary control are whatever you've specified in the ErrorMessage properties of the Validation controls. To change the in-line error message, use the Text property:

1: <asp:RequiredFieldValidator runat="server"
2:  ControlToValidate="tbFName"
3:  ErrorMessage="First name required"
4:  Text="Forgot first name!"
5:  Display="dynamic"/>

The first name validator will now display "Forgot first name!" beneath the first name text box and "First name required" in the ValidationSummary control. If you don't want to display the in-line error messages, you can set each control's Display property to none.

By adding the ShowMessageBox property, you can create a pop-up message box with the ValidationSummary control. For example, change the previous summary code snippet to read as follows:

1: <asp:ValidationSummary runat="server"
2:  ShowMessageBox="true"
3:  DisplayMode="BulletList" />

After entering invalid information and clicking Submit, you should see the dialog box in Figure 7.9.

Figure 7.9 Alerting users with a pop-up box.

Table 7.5 summarizes the parameters required to display the Validation control error messages in a variety of formats and positions.

Table 7.5 Error Message Layout Parameters

Type

ValidationSummary

Validation Control Settings

In-line

Not required

Display = Static or Dynamic

 

 

ErrorMessage = In-line error text

Summary

Required

Display = None

 

 

ErrorMessage = Summary error text

Both

Required

Display = Static or Dynamic

 

 

ErrorMessage = Summary error text

 

 

Text = In-line error text


You can set the Text property of the Validation controls to any valid HTML tags. This means you can use images to display your error messages or provide links to further descriptions!

Finally, you can customize each error message with the typical style properties available to any server control. For example:

  • ForeColor—The color of the error message text

  • BackColor—The color behind the text

  • Font—The font face, size, weight, and so on

  • BorderWidth, BorderColor, and BorderStyle—The size and color of the border around the error message

  • CSSStyle and CSSClass—Style settings pulled from cascading style sheets

For more information, see the common property list in Appendix C, "ASP.NET Controls: Properties and Methods."

Custom Validation Controls

If none of the predefined Validation controls suit your needs, you can easily create your own customized Validation controls. For example, some Web sites require you to choose a user name when you register with them. This user name often needs to be of a certain length. None of the existing Validation controls check the length of user input, so you have to do this manually.

With the CustomValidator control, you can easily define any type of validation you need by using the familiar Validation control syntax. This control only provides the framework for your custom validation; you must build the actual routine yourself. In other words, you can use this control to watch over another server control. When the user enters data, the CustomValidator will execute a method that you've built.

For example, Listing 7.7 shows a typical login form for a secure Web site.

Listing 7.7 Using a Custom Validator

 1: <%@ Page Language="VB" %>
 2:
 3: <script runat="server">
 4:  sub Submit(obj as object, e as eventargs)
 5:   'do something
 6:  end sub
 7:
 8:sub ValidateThis(obj as Object, args as _
 9: ServerValidateEventArgs)
10: if len(args.Value) < 8 then
11:  args.IsValid = false
12: else
13:  args.IsValid = true
14: end if
15:end sub
16: </script>
17:
18: <html><body>
19:  <form runat="server">
20:   <asp:Label id="lblMessage" runat="server" />
21:   <table>
22:   <tr>
23:    <td valign="top">Username:</td>
24:    <td valign="top">
25:    <asp:Textbox id="tbUserName" runat="server" />
26:    <br>
27:    <asp:CustomValidator runat="server"
28:     OnServerValidate="ValidateThis"
29:     Display="Dynamic"
30:     ControlToValidate="tbUserName"
31:     ErrorMessage="The username must be 8
32:    characters or longer"/>
33:    </td>
34:   </tr>
35:   <tr>
36:    <td valign="top">Password:</td>
37:    <td valign="top">
38:    <asp:Textbox id="tbPassword" runat="server"
39:     TextMode="password" />
40:    </td>
41:   </tr>
42:   <tr>
43:    <td align="right" colspan="2">
44:    <ASP:Button id="tbSubmit" runat="server"
45:     OnClick="Submit"
46:     text="Submit" />
47:    </td>
48:   </tr>
49:   </table>
50:  </form>
51: </body></html>

On line 27, you see the CustomValidator control. It's similar to all of the other Validation controls you've looked at so far, with the ControlToValidate, ErrorMessage, and Display properties. However, there's one new property: OnServerValidate. This property is used to specify the event handler that should handle the validation.

Let's look at the code declaration block. On line 4, you have your Submit method, which doesn't do anything yet. Recall from Day 5, "Beginning Web Forms," that Web form events are processed in no particular order. The ServerValidate event of the CustomValidator control is the only major exception to that rule. This event will always be processed first so that any other methods can check for validity on the Page object.

On line 8 is your event handler for the ServerValidate event. Notice that the parameter list is different from what you're used to. The second parameter, args, is a ServerValidateEventArgs object that contains the user input in question. Use the Value property to retrieve the text contained in this object, and the IsValid property to set the validity of the custom validator control.

In your function, you check if the length of the input is less than eight characters (using the Len function). If it is, the input is invalid and you return false. When you fill out this form and click Submit, you should see what's shown in Figure 7.10.

Figure 7.10 Your custom validator allows you to perform customized validation checks.

The custom validator event handler can be used to validate information however you want. You can even use custom validation to check values against a database on the server!

To test your validator, add the following code to the Submit method on line 4:

5: if Page.IsValid then
6:  lblMessage.Text = "It's all good!"
7:  'do some other processing
8: end if

This method will handle the form submission once all fields are valid. However, the validation handler will execute first and return a Boolean value specifying whether or not the input is valid. If it's valid, the CustomValidator control sets its IsValid property to true, and Page.IsValid evaluates to true as well.

The CustomValidator also allows you to validate on the client-side. To do this, you need to create a JavaScript event handler that resides on the client. For example, the following script block performs the same validation routine as Listing 7.7, only in JavaScript on the client-side:

1: <script language="JavaScript">
2:  function validateLength( oSrc, txtValue ){
3:   var retValue = true; // assume ok
4:   if(txtValue.length < 8){
5:    retValue = false;}
6:   return retValue
7:  }
8: </script>

Add this script block to Listing 7.7, directly below the existing code declaration block. Then, in the CustomValidator control, you must set the OnClientSideValidate property to the JavaScript method:

27: <asp:CustomValidator runat="server"
28:  OnServerValidate="ValidateThis" 
29:  OnClientSideValidate="validateLength"" 
30:  Display="Dynamic"
31:  ControlToValidate="tbUserName"
32:  ErrorMessage="The username must be 8 characters or longer"/>

When you view this page from the browser, you'll have the same dynamic error-display capabilities you had with the other Validation controls. When the user inputs invalid information and moves to another control, the JavaScript method executes and returns false, setting the CustomValidator's IsValid property to false as well. The dynamic error message will be displayed automatically without having to post information to the server! Of course, you can still use your server validation routine as an additional check.

  • + 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