Overview of the Validation Controls


Six validation controls are included in the ASP.NET 2.0 Framework:

  • RequiredFieldValidator Enables you to require a user to enter a value in a form field.

  • RangeValidator Enables you to check whether a value falls between a certain minimum and maximum value.

  • CompareValidator Enables you to compare a value against another value or perform a data type check.

  • RegularExpressionValidator Enables you to compare a value against a regular expression.

  • CustomValidator Enables you to perform custom validation.

  • ValidationSummary Enables you to display a summary of all validation errors in a page.

You can associate the validation controls with any of the form controls included in the ASP.NET Framework. For example, if you want to require a user to enter a value into a TextBox control, then you can associate a RequiredFieldValidator control with the TextBox control.

Note

Technically, you can use the validation controls with any control that is decorated with the ValidationProperty attribute.


The page in Listing 3.1 contains a simple order entry form. It contains three TextBox controls that enable you to enter a product name, product price, and product quantity. Each of the form fields are validated with the validation controls.

Listing 3.1. OrderForm.aspx

<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server">     Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs)         If Page.IsValid Then             lblResult.Text = "<br />Product: " & txtProductName.Text             lblResult.Text &= "<br />Price: " & txtProductPrice.Text             lblResult.Text &= "<br />Quantity: " & txtProductQuantity.Text         End If     End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head  runat="server">     <title>Order Form</title> </head> <body>     <form  runat="server">     <div>     <fieldset>     <legend>Product Order Form</legend>     <asp:Label                  Text="Product Name:"         AssociatedControl         Runat="server" />     <br />     <asp:TextBox                  Runat="server" />     <asp:RequiredFieldValidator                  ControlToValidate="txtProductName"         Text="(Required)"         Runat="server" />     <br /><br />     <asp:Label                  Text="Product Price:"         AssociatedControl         Runat="server" />     <br />     <asp:TextBox                  Columns="5"         Runat="server" />     <asp:RequiredFieldValidator                  ControlToValidate="txtProductPrice"         Text="(Required)"         Display="Dynamic"         Runat="server" />     <asp:CompareValidator                  ControlToValidate="txtProductPrice"         Text="(Invalid Price)"         Operator="DataTypeCheck"         Type="Currency"         Runat="server" />     <br /><br />     <asp:Label                  Text="Product Quantity:"         AssociatedControl         Runat="server" />     <br />     <asp:TextBox                  Columns="5"         Runat="server" />     <asp:RequiredFieldValidator                  ControlToValidate="txtProductQuantity"         Text="(Required)"         Display="Dynamic"         Runat="server" />     <asp:CompareValidator                  ControlToValidate="txtProductQuantity"         Text="(Invalid Quantity)"         Operator="DataTypeCheck"         Type="Integer"         Runat="server" />     <br /><br />     <asp:Button                  Text="Submit Product Order"         OnClick="btnSubmit_Click"         Runat="server" />     </fieldset>     <asp:Label                  Runat="server" />     </div>     </form> </body> </html> 

A separate RequiredFieldValidator control is associated with each of the three form fields. If you attempt to submit the form in Listing 3.1 without entering a value for a field, then a validation error message is displayed (see Figure 3.1).

Figure 3.1. Displaying a validation error message.


Each RequiredFieldValidator is associated with a particular control through its ControlToValidate property. This property accepts the name of the control to validate on the page.

CompareValidator controls are associated with the txtProductPrice and txtProductQuantity TextBox controls. The first CompareValidator is used to check whether the txtProductPrice text field contains a currency value, and the second CompareValidator is used to check whether the txtProductQuantity text field contains an integer value.

Notice that there is nothing wrong with associating more than one validation control with a form field. If you need to make a form field required and check the data type entered into the form field, then you need to associate both a RequiredFieldValidator and CompareValidator control with the form field.

Finally, notice that the Page.IsValid property is checked in the btnSubmit_Click() handler after the form data is submitted. When using the validation controls, you should always check the Page.IsValid property before doing anything with the data submitted to a page. This property returns the value true when, and only when, there are no validation errors on the page.

Validation Controls and JavaScript

By default, the validation controls perform validation on both the client (the browser) and the server. The validation controls use client-side JavaScript. This is great from a user experience perspective because you get immediate feedback whenever you enter an invalid value into a form field.

Note

The RequiredFieldValidator will not perform client-side validation until after you attempt to submit a form at least once or you enter and remove data in a form field.


Client-side JavaScript is supported on any uplevel browser. Supported browsers include Internet Explorer, Firefox, and Opera. This is a change from the previous version of ASP.NET, which supported only Internet Explorer as an uplevel browser.

You can use the validation controls with browsers that do not support JavaScript (or do not have JavaScript enabled). If a browser does not support JavaScript, the form must be posted back to the server before a validation error message is displayed.

Even when validation happens on the client, validation is still performed on the server. This is done for security reasons. If someone creates a fake form and submits the form data to your web server, the person still won't be able to submit invalid data.

If you prefer, you can disable client-side validation for any of the validation controls by assigning the value False to the validation control's EnableClientScript property.

Using Page.IsValid

As mentioned earlier, you should always check the Page.IsValid property when working with data submitted with a form that contains validation controls. Each of the validation controls includes an IsValid property that returns the value true when there is not a validation error. The Page.IsValid property returns the value true when the IsValid property for all of the validation controls in a page returns the value TRue.

It is easy to forget to check the Page.IsValid property. When you use an uplevel browser that supports JavaScript with the validation controls, you are prevented from submitting a form back to the server when there are validation errors. However, if someone requests a page using a browser that does not support JavaScript, the page is submitted back to the server even when there are validation errors.

For example, if you request the page in Listing 3.1 with a browser that does not support JavaScript and submit the form without entering form data, then the btnSubmit_Click() handler executes on the server. The Page.IsValid property is used in Listing 3.1 to prevent downlevel browsers from displaying invalid form data.

Warning

Unfortunately, I've made the mistake of forgetting to include a check of the Page.IsValid property several times when building applications. Because you do not normally develop a web application with a downlevel browser, you won't notice the problem described in this section until you start getting invalid data in your database tables.


Setting the Display Property

All the validation controls include a Display property that determines how the validation error message is rendered. This property accepts any of the following three possible values:

  • Static

  • Dynamic

  • None

By default, the Display property has the value Static. When the Display property has this value, the validation error message rendered by the validation control looks like this:

<span  style="color:Red;visibility:hidden;">(Required)</span> 


Notice that the error message is rendered in a <span> tag that includes a Cascading Style Sheet style attribute that sets the visibility of the <span> tag to hidden.

If, on the other hand, you set the Display property to the value Dynamic, the error message is rendered like this:

<span  style="color:Red;display:none;">(Required)</span> 


In this case, a Cascading Style Sheet display attribute hides the contents of the <span> tag.

Both the visibility and display attributes can be used to hide text in a browser. However, text hidden with the visibility attribute still occupies screen real estate. Text hidden with the display attribute, on the other hand, does not occupy screen real estate.

In general, you should set a validation control's Display property to the value Dynamic. That way, if other content is displayed next to the validation control, the content is not pushed to the right. All modern browsers (Internet Explorer, Firefox, and Opera) support the Cascading Style Sheet display attribute.

The third possible value of the Display property is None. If you prefer, you can prevent the individual validation controls from displaying an error message and display the error messages with a ValidationSummary control. You learn how to use the ValidationSummary control later in this chapter.

Highlighting Validation Errors

When a validation control displays a validation error, the control displays the value of its Text property. Normally, you assign a simple text string, such as "(Required)" to the Text property. However, the Text property accepts any HTML string.

For example, the page in Listing 3.2 displays an image when you submit the form without entering a value for the First Name text field (see Figure 3.2).

Figure 3.2. Displaying an image for a validation error.


Listing 3.2. ValidationImage.aspx

<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head  runat="server">     <title>Validation Image</title> </head> <body>     <form  runat="server">     <div>     <asp:Label                  Text="First Name"         AssociatedControl         Runat="server" />     <br />     <asp:TextBox                  Runat="server" />     <asp:RequiredFieldValidator                  ControlToValidate="txtFirstName"         Text="<img src='/books/3/444/1/html/2/Error.gif' alt='First name is required.' />"         Runat="server" />      <br /><br />      <asp:Button                  Text="Submit"         Runat="server" />     </div>     </form> </body> </html> 

In Listing 3.2, the Text property contains an HTML <img> tag. When there is a validation error, the image represented by the <img> tag is displayed.

Another way that you can emphasize errors is to take advantage of the SetFocusOnError property that is supported by all the validation controls. When this property has the value TRue, the form focus is automatically shifted to the control associated with the validation control when there is a validation error.

For example, the page in Listing 3.3 contains two TextBox controls that are both validated with RequiredFieldValidator controls. Both RequiredFieldValidator controls have their SetFocusOnError properties enabled. If you provide a value for the first text field and not the second text field and submit the form, the form focus automatically shifts to the second form field.

Listing 3.3. ShowSetFocusOnError.aspx

<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" > <head  runat="server">     <title>Show SetFocusOnError</title> </head> <body>     <form  runat="server">     <div>     <asp:Label                  Text="First Name"         AssociatedControl         Runat="server" />     <br />     <asp:TextBox                  Runat="server" />     <asp:RequiredFieldValidator                  ControlToValidate="txtFirstName"         Text="(Required)"         SetFocusOnError="true"         Runat="server" />     <br /><br />     <asp:Label                  Text="Last Name"         AssociatedControl         Runat="server" />     <br />     <asp:TextBox                  Runat="server" />     <asp:RequiredFieldValidator                  ControlToValidate="txtLastName"         Text="(Required)"         SetFocusOnError="true"         Runat="server" />      <br /><br />      <asp:Button                  Text="Submit"         Runat="server" />     </div>     </form> </body> </html> 

Finally, if you want to really emphasize the controls associated with a validation error, then you can take advantage of the Page.Validators property. This property exposes the collection of all the validation controls in a page. In Listing 3.4, the Page.Validators property is used to highlight each control that has a validation error (see Figure 3.3).

Figure 3.3. Changing the background color of form fields.


Listing 3.4. ShowValidators.aspx

<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server">     Sub Page_PreRender()         For Each valControl As BaseValidator In Page.Validators             Dim assControl As WebControl = Page.FindControl(valControl.ControlToValidate)             If Not valControl.IsValid Then                 assControl.BackColor = Drawing.Color.Yellow             Else                 assControl.BackColor = Drawing.Color.White             End If         Next     End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head  runat="server">     <title>Show Validators</title> </head> <body>     <form  runat="server">     <div>     <asp:Label                  Text="First Name"         AssociatedControl         Runat="server" />     <br />     <asp:TextBox                  Runat="server" />     <asp:RequiredFieldValidator                  ControlToValidate="txtFirstName"         Text="(Required)"         EnableClientScript="false"         Runat="server" />     <br /><br />     <asp:Label                  Text="Last Name"         AssociatedControl         Runat="server" />     <br />     <asp:TextBox                  Runat="server" />     <asp:RequiredFieldValidator                  ControlToValidate="txtLastName"         Text="(Required)"         EnableClientScript="false"         Runat="server" />      <br /><br />      <asp:Button                  Text="Submit"         Runat="server" />     </div>     </form> </body> </html> 

The Page.Validators property is used in the Page_PreRender() handler. The IsValid property is checked for each control in the Page.Validators collection. If IsValid returns False, then the control being validated by the validation control is highlighted with a yellow background color.

Using Validation Groups

In the first version of the ASP.NET Framework, there was no easy way to add two forms to the same page. If you added more than one form to a page, and both forms contained validation controls, then the validation controls in both forms were evaluated regardless of which form you submitted.

For example, imagine that you wanted to create a page that contained both a login and registration form. The login form appeared in the left column and the registration form appeared in the right column. If both forms included validation controls, then submitting the login form caused any validation controls contained in the registration form to be evaluated.

In ASP.NET 2.0, you no longer face this limitation. The ASP.NET 2.0 Framework introduces the idea of validation groups. A validation group enables you to group related form fields together.

For example, the page in Listing 3.5 contains both a login and registration form and both forms contain independent sets of validation controls.

Listing 3.5. ShowValidationGroups.aspx

<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server">     Protected Sub btnLogin_Click(ByVal sender As Object, ByVal e As EventArgs)         If Page.IsValid() Then             lblLoginResult.Text = "Log in successful!"         End If     End Sub     Protected Sub btnRegister_Click(ByVal sender As Object, ByVal e As EventArgs)         If Page.IsValid() Then             lblRegisterResult.Text = "Registration successful!"         End If     End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head  runat="server">     <style type="text/css">         html         {             background-color:silver;         }         .column         {             float:left;             width:300px;             margin-left:10px;             background-color:white;             border:solid 1px black;             padding:10px;         }     </style>     <title>Show Validation Groups</title> </head> <body>     <form  runat="server">     <div >     <fieldset>     <legend>Login</legend>     <p>     Please log in to our Website.     </p>     <asp:Label                  Text="User Name:"         AssociatedControl         Runat="server" />     <br />     <asp:TextBox                  Runat="server" />     <asp:RequiredFieldValidator                  ControlToValidate="txtUserName"         Text="(Required)"         ValidationGroup="LoginGroup"         Runat="server" />     <br /><br />     <asp:Label                  Text="Password:"         AssociatedControl         Runat="server" />     <br />     <asp:TextBox                  TextMode="Password"         Runat="server" />     <asp:RequiredFieldValidator                  ControlToValidate="txtPassword"         Text="(Required)"         ValidationGroup="LoginGroup"         Runat="server" />     <br /><br />     <asp:Button                  Text="Login"         ValidationGroup="LoginGroup"         Runat="server" OnClick="btnLogin_Click" />     </fieldset>     <asp:Label                  Runat="server" />     </div>     <div >     <fieldset>     <legend>Register</legend>     <p>     If you do not have a User Name, please     register at our Website.     </p>     <asp:Label                  Text="First Name:"         AssociatedControl         Runat="server" />     <br />     <asp:TextBox                  Runat="server" />     <asp:RequiredFieldValidator                  ControlToValidate="txtFirstName"         Text="(Required)"         ValidationGroup="RegisterGroup"         Runat="server" />     <br /><br />     <asp:Label                  Text="Last Name:"         AssociatedControl         Runat="server" />     <br />     <asp:TextBox                  Runat="server" />     <asp:RequiredFieldValidator                  ControlToValidate="txtLastName"         Text="(Required)"         ValidationGroup="RegisterGroup"         Runat="server" />     <br /><br />     <asp:Button                  Text="Register"         ValidationGroup="RegisterGroup"         Runat="server" OnClick="btnRegister_Click" />     </fieldset>     <asp:Label                  Runat="server" />     </div>     </form> </body> </html> 

Notice that the validation controls and the button controls all include ValidationGroup properties. The controls associated with the login form all have the value "LoginGroup" assigned to their ValidationGroup properties. The controls associated with the register form all have the value "RegisterGroup" assigned to their ValidationGroup properties.

Because the form fields are grouped into different validation groups, you can submit the two forms independently. Submitting the Login form does not trigger the validation controls in the Register form (see Figure 3.4).

Figure 3.4. Using validation groups.


You can assign any string to the ValidationGroup property. The only purpose of the string is to associate different controls in a form together into different groups.

Note

Using validation groups is particularly important when working with Web Parts because multiple Web Parts with different forms might be added to the same page.


Disabling Validation

All the button controlsthe Button, LinkButton, and ImageButton controlinclude a CausesValidation property. If you assign the value False to this property, then clicking the button bypasses any validation in the page.

Bypassing validation is useful when creating a Cancel button. For example, the page in Listing 3.6 includes a Cancel button that redirects the user back to the Default.aspx page.

Listing 3.6. ShowDisableValidation.aspx

<%@ Page Language="VB" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <script runat="server">     Protected Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs)         Response.Redirect("~/Default.aspx")     End Sub </script> <html xmlns="http://www.w3.org/1999/xhtml" > <head  runat="server">     <title>Show Disable Validation</title> </head> <body>     <form  runat="server">     <div>     <asp:Label                  Text="First Name:"         AssociatedControl         Runat="server" />     <asp:TextBox                  Runat="server" />     <asp:RequiredFieldValidator                  ControlToValidate="txtFirstName"         Text="(Required)"         Runat="server" />     <br /><br />     <asp:Button                  Text="Submit"         Runat="server" />     <asp:Button                  Text="Cancel"         OnClick="btnCancel_Click"         CausesValidation="false"         Runat="server" />     </div>     </form> </body> </html> 

Notice that the Cancel button in Listing 3.6 includes the CausesValidation property with the value False. If the button did not include this property, then the RequiredFieldValidator control would prevent you from submitting the form when you clicked the Cancel button.




ASP. NET 2.0 Unleashed
ASP.NET 2.0 Unleashed
ISBN: 0672328232
EAN: 2147483647
Year: 2006
Pages: 276

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net