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 controls 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
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.
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(Sender 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 runat="server" /><p> 14: 15: Enter your name: 16: <asp:TextBox runat="server" /><br> 17: <asp:RequiredFieldValidator runat="server" 18: ControlToValidate="tbFName" 19: ErrorMessage="First name required"/><p> 20: 21: <asp:Button 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.
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
| || |
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 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 the server and client sides.
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 still 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.