Customizing Validation


Sams Teach Yourself ASP.NET in 21 Days, Second Edition
By Chris Payne
Table of Contents
Day 7.  Validating ASP.NET Pages

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" /> 
Figure 7.6. The error message seems out-of-place because other Validation controls are in the way.


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.7. Dynamic display eliminates the white space problem.


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


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 username when you register with them. This username 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(Sender as Object, e as EventArgs) 5:          'do something 6:       end sub 7: 8:       sub ValidateThis(Sender 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 function 16:    </script> 17: 18:    <html><body> 19:       <form runat="server"> 20:          <asp:Label  runat="server" /> 21:          <table> 22:          <tr> 23:             <td valign="top">Username:</td> 24:             <td valign="top"> 25:                <asp:Textbox  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  runat="server" 39:                   TextMode="password" /> 40:             </td> 41:          </tr> 42:          <tr> 43:             <td align="right" colspan="2"> 44:                <ASP:Button  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 control that contains the user input in question.

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 youset the IsValid property to 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:       OnClientValiate="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.


    Sams Teach Yourself ASP. NET in 21 Days
    Sams Teach Yourself ASP.NET in 21 Days (2nd Edition)
    ISBN: 0672324458
    EAN: 2147483647
    Year: 2003
    Pages: 307
    Authors: Chris Payne

    Similar book on Amazon © 2008-2017.
    If you may any questions please contact us: