Using the Validation Controls in ASP.NET 2.0
- Overview of the Validation Controls
- Using the RequiredFieldValidator Control
- Using the RangeValidator Control
- Using the CompareValidator Control
- Using the RegularExpressionValidator Control
- Using the CustomValidator Control
- Using the ValidationSummary Control
- Creating Custom Validation Controls
- Summary
Overview of the Validation Controls
Using the RequiredFieldValidator Control
Using the RangeValidator Control
Using the CompareValidator Control
Using the RegularExpressionValidator Control
Using the CustomValidator Control
Using the ValidationSummary Control
Creating Custom Validation Controls
Summary
In this chapter, you learn how to validate form fields when a form is submitted to the web server. You can use the validation controls to prevent users from submitting the wrong type of data into a database table. For example, you can use validation controls to prevent a user from submitting the value "Apple" for a birth date field.
In the first part of this chapter, you are provided with an overview of the standard validation controls included in the ASP.NET 2.0 Framework. You learn how to control how validation errors are displayed, how to highlight validation error messages, and how to use validation groups. You are provided with sample code for using each of the standard validation controls.
Next, we extend the basic validation controls with our own custom validation controls. For example, you learn how to create an AjaxValidator control that enables you to call a server-side validation function from the client.
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.
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.
Example 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 id="Head1" runat="server"> <title>Order Form</title> </head> <body> <form id="form1" runat="server"> <div> <fieldset> <legend>Product Order Form</legend> <asp:Label id="lblProductName" Text="Product Name:" AssociatedControlID="txtProductName" Runat="server" /> <br /> <asp:TextBox id="txtProductName" Runat="server" /> <asp:RequiredFieldValidator id="reqProductName" ControlToValidate="txtProductName" Text="(Required)" Runat="server" /> <br /><br /> <asp:Label id="lblProductPrice" Text="Product Price:" AssociatedControlID="txtProductPrice" Runat="server" /> <br /> <asp:TextBox id="txtProductPrice" Columns="5" Runat="server" /> <asp:RequiredFieldValidator id="reqProductPrice" ControlToValidate="txtProductPrice" Text="(Required)" Display="Dynamic" Runat="server" /> <asp:CompareValidator id="cmpProductPrice" ControlToValidate="txtProductPrice" Text="(Invalid Price)" Operator="DataTypeCheck" Type="Currency" Runat="server" /> <br /><br /> <asp:Label id="lblProductQuantity" Text="Product Quantity:" AssociatedControlID="txtProductQuantity" Runat="server" /> <br /> <asp:TextBox id="txtProductQuantity" Columns="5" Runat="server" /> <asp:RequiredFieldValidator id="reqProductQuantity" ControlToValidate="txtProductQuantity" Text="(Required)" Display="Dynamic" Runat="server" /> <asp:CompareValidator id="CompareValidator1" ControlToValidate="txtProductQuantity" Text="(Invalid Quantity)" Operator="DataTypeCheck" Type="Integer" Runat="server" /> <br /><br /> <asp:Button id="btnSubmit" Text="Submit Product Order" OnClick="btnSubmit_Click" Runat="server" /> </fieldset> <asp:Label id="lblResult" 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.
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.
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 id="reqProductName" 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 id="reqProductName" 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.
Example 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 id="Head1" runat="server"> <title>Validation Image</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label id="lblFirstName" Text="First Name" AssociatedControlID="txtFirstName" Runat="server" /> <br /> <asp:TextBox id="txtFirstName" Runat="server" /> <asp:RequiredFieldValidator id="reqFirstName" ControlToValidate="txtFirstName" Text="<img src='Error.gif' alt='First name is required.' />" Runat="server" /> <br /><br /> <asp:Button id="btnSubmit" 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.
Example 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 id="Head1" runat="server"> <title>Show SetFocusOnError</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label id="lblFirstName" Text="First Name" AssociatedControlID="txtFirstName" Runat="server" /> <br /> <asp:TextBox id="txtFirstName" Runat="server" /> <asp:RequiredFieldValidator id="reqFirstName" ControlToValidate="txtFirstName" Text="(Required)" SetFocusOnError="true" Runat="server" /> <br /><br /> <asp:Label id="lblLastName" Text="Last Name" AssociatedControlID="txtLastName" Runat="server" /> <br /> <asp:TextBox id="txtLastname" Runat="server" /> <asp:RequiredFieldValidator id="reqLastName" ControlToValidate="txtLastName" Text="(Required)" SetFocusOnError="true" Runat="server" /> <br /><br /> <asp:Button id="btnSubmit" 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.
Example 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 id="Head1" runat="server"> <title>Show Validators</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label id="lblFirstName" Text="First Name" AssociatedControlID="txtFirstName" Runat="server" /> <br /> <asp:TextBox id="txtFirstName" Runat="server" /> <asp:RequiredFieldValidator id="reqFirstName" ControlToValidate="txtFirstName" Text="(Required)" EnableClientScript="false" Runat="server" /> <br /><br /> <asp:Label id="lblLastName" Text="Last Name" AssociatedControlID="txtLastName" Runat="server" /> <br /> <asp:TextBox id="txtLastname" Runat="server" /> <asp:RequiredFieldValidator id="reqLastName" ControlToValidate="txtLastName" Text="(Required)" EnableClientScript="false" Runat="server" /> <br /><br /> <asp:Button id="btnSubmit" 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.
Example 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 id="Head1" 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 id="form1" runat="server"> <div class="column"> <fieldset> <legend>Login</legend> <p> Please log in to our Website. </p> <asp:Label id="lblUserName" Text="User Name:" AssociatedControlID="txtUserName" Runat="server" /> <br /> <asp:TextBox id="txtUserName" Runat="server" /> <asp:RequiredFieldValidator id="reqUserName" ControlToValidate="txtUserName" Text="(Required)" ValidationGroup="LoginGroup" Runat="server" /> <br /><br /> <asp:Label id="lblPassword" Text="Password:" AssociatedControlID="txtPassword" Runat="server" /> <br /> <asp:TextBox id="txtPassword" TextMode="Password" Runat="server" /> <asp:RequiredFieldValidator id="reqPassword" ControlToValidate="txtPassword" Text="(Required)" ValidationGroup="LoginGroup" Runat="server" /> <br /><br /> <asp:Button id="btnLogin" Text="Login" ValidationGroup="LoginGroup" Runat="server" OnClick="btnLogin_Click" /> </fieldset> <asp:Label id="lblLoginResult" Runat="server" /> </div> <div class="column"> <fieldset> <legend>Register</legend> <p> If you do not have a User Name, please register at our Website. </p> <asp:Label id="lblFirstName" Text="First Name:" AssociatedControlID="txtFirstName" Runat="server" /> <br /> <asp:TextBox id="txtFirstName" Runat="server" /> <asp:RequiredFieldValidator id="reqFirstName" ControlToValidate="txtFirstName" Text="(Required)" ValidationGroup="RegisterGroup" Runat="server" /> <br /><br /> <asp:Label id="lblLastName" Text="Last Name:" AssociatedControlID="txtLastName" Runat="server" /> <br /> <asp:TextBox id="txtLastName" Runat="server" /> <asp:RequiredFieldValidator id="reqLastName" ControlToValidate="txtLastName" Text="(Required)" ValidationGroup="RegisterGroup" Runat="server" /> <br /><br /> <asp:Button id="btnRegister" Text="Register" ValidationGroup="RegisterGroup" Runat="server" OnClick="btnRegister_Click" /> </fieldset> <asp:Label id="lblRegisterResult" 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.
Disabling Validation
All the button controls—the Button, LinkButton, and ImageButton control—include 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.
Example 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 id="Head1" runat="server"> <title>Show Disable Validation</title> </head> <body> <form id="form1" runat="server"> <div> <asp:Label id="lblFirstName" Text="First Name:" AssociatedControlID="txtFirstName" Runat="server" /> <asp:TextBox id="txtFirstName" Runat="server" /> <asp:RequiredFieldValidator id="reqFirstName" ControlToValidate="txtFirstName" Text="(Required)" Runat="server" /> <br /><br /> <asp:Button id="btnSubmit" Text="Submit" Runat="server" /> <asp:Button id="btnCancel" 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.