A common problem for developers is ensuring that data entered by users is valid. That problem is made more diffi cult when your application exists in a Web browser. When the data is sent from the browser to the server you need to make sure that data is valid. In addition, users expect some feedback and assistance entering valid data before they spend the time sending it back to the server for a response.
Client-side validation is a convenience to users. It improves performance by checking the data at the browser before sending the data to the server. This avoids unnecessary round trips to the server. However, client-side validation can be easily defeated by hackers. Server-side validation is the only secure means of validating the data that is posted back to the server.
Using both client-side and server-side validation provides a better experience to the user and secure validation for your Web site.
Adding Validation Controls to Your Page
Validation controls are found in the Visual Studio toolbox and are added to a Web page like other controls. The following are the basic steps for using a validation control on a Web page:
1. Open a Web page in Design view and open the Visual Studio Toolbox. Navigate to the Validation tab of the toolbox.
2. Drag and drop the desired validation control next to (or near) the control you intend to validate. For example, you might drag a RequiredFieldValidator control next to a TextBox control to ensure a user enters data in the text box.
3. Next, you set the ID property of the validation control (from Source view or in the Properties window). Of course, it is important to name it similarly to the field it validates.
4. The next step is to set the validation control’s ControlToValidate property. Here you can select another control already on the page. This is the control that the validation control will validate.
5. The ErrorMessage property of the validation control should also be set. The values set as the ErrorMessage will be displayed to users as assistance when they try to submit the form with invalid data. This message is typically put into a ValidationSummary control on the page.
6. It is a good idea to also set the validation control’s ToolTip property to be the same as or similar to the ErrorMessage property. This value will display when the user hovers the pointer over the validation control’s text (during an invalid operation).
7. Finally, you set the Text property of the validation control to a short string. This might be an asterisk (*), for example. Keeping this short minimizes the space that is required by the validation control but still offers a visual cue to the user that something is wrong with the given item.
Creating a Summary of Validation Errors
You should also consider adding a ValidationSummary control to your data input pages. This control is placed on a Web page to display all the validation error messages in one location after the user has triggered page-level validation by clicking a submit button. This is especially useful in scenarios where the Web page is crowded with other controls and displaying the validation error message next to the invalid control presents a difficult layout situation.
The ValidationSummary control can also be configured to display a pop-up message with the validation errors in lieu of, or in addition to, displaying the validation errors on the Web page.
Using Validation Groups
Often you do not want to treat your entire page as a single entity that is validated as a whole. Instead, you might want to break up sections of the page and have them validated independently. This is especially true for long data entry forms with multiple sections. You might not want the entire page’s validation to fire when only submitting a single section of the page. The validation controls in ASP.NET have the property ValidationGroup attached to them. This property can be assigned a string value to specify a section of your page (or group of controls to validate as a single unit). This property exists on the validation controls and on the controls that cause a PostBack. When a control performs a PostBack, the validation controls that have a matching ValidationGroup property value are validated. This allows for these controls to validate as a unit.
When you hit the server (following PostBack), the IsValid property on the Page object only reflects the validity of the validation controls that have been validated. By default, these are the validation controls that are in the same ValidationGroup, but you can call a validation control’s Validate method to add that control to the set of controls on which the IsValid property reports.
There is also an overload method to the Page object’s Validate method. This overload accepts a string used to specify the ValidationGroup to validate. This overload is executed when a PostBack that causes validation occurs. The Page object also has a GetValidators method that accepts a string containing the name of the ValidationGroup. This method returns the list of validation controls in the given ValidationGroup.
Understanding the BaseCompareValidator Class
The RangeValidator and CompareValidator controls inherit from the BaseCompareValidator control. This base class contains common comparison behavior used by these controls. The BaseCompareValidator contains the Type property, which you can set to the data type that the text is converted to before a comparison is made. The data types that are available are as follows:
- Currency The data is validated as System.Decimal, but currency symbols and grouping characters also can be entered.
- Date The data is validated as a numeric date.
- Double The data is validated as System.Double.
- Integer The data is validated as System.Int32.
- String The data is validated as System.String.
The BaseCompareValidator class is, of course, a base class and not an actual validation control.
Using the CompareValidator Control
The CompareValidator control performs validation by using comparison operators such as greater than and less than to compare the data entered by a user with a constant you set or a value in a different control.
The CompareValidator can also be used to verify that the data entered into a given control is of a certain data type, such as a date or a number. To do so, you set the Type property to a valid data type. ASP.NET will then validate that the user’s input can be cast into a valid instance of the given type. If all you intend is a data type check, you can also set the Operator property to DataTypeCheck.
The CompareValidator control uses the property ValueToCompare to set a constant that is used to perform a comparison.
You would then set the Operator property of the control. This property defines how to perform the comparison and can be set to Equal, NotEqual, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual, or DataTypeCheck. In the case of the birth date example, you would set this value to GreaterThanEqual.
You can also use the ControlToCompare property to define another control that is used to perform the comparison.
Using the RangeValidator Control
You often need to validate that a value entered by a user is within a predefined range of acceptable values. For example, you might want to write a Web page that shows sales for the current year up through a specific date. You would then want to verify that the user has entered a date value that is within the range of the current year. To do so, you can use the RangeValidator control.
The RangeValidator control verifies that user input is within a specified range of values. This control has two very specific properties for managing the range of acceptable values: MinimumValue and MaximumValue. These properties work as their name indicates.
Using the RegularexpressionValidator Control
The RegularExpressionValidator control performs its validation based on a regular expression. A regular expression is a powerful pattern-matching language that can be used to identify simple and complex character sequences that would otherwise require writing code to accomplish. The control uses the ValidationExpression property to set a valid regular expression that is applied to the data that is to be validated. The data is validated if it matches the regular expression.
Custom Server-Side Validation
To implement server-side validation with the CustomValidator control, you override its ServerValidate event. This server-side event can be trapped in your code-behind file to execute code that you write. You wire up an event handler for the given CustomValidator control the same way you would any other control’s event.
Choosing a Method to Navigate Pages
There are many ways to navigate from one page to another in ASP.NET. It’s helpful to first identify these ways and then examine each in detail. The following are the methods for pagetopage navigation in an ASP.NET site:
- Cross-page posting A control and form are configured to PostBack to a different Web page than the one that made the original request.
- Client-side browser redirect Server-side code sends a message to the browser, informing the browser to request a different Web page from the server.
- Server-side transfer Server-side code transfers control of a request to a different Web page.
One of the easiest ways to navigate to a different Web page is to provide a HyperLink control on the form and set the NavigateUrl property to the desired destination. The HyperLink control generates an HTML anchor tag, <a>. The NavigateUrl property is placed into the href attribute of the <a> element. The following example shows both the source of a HyperLink control and its rendered HTML.
HyperLink Control: Source
runat="server" NavigateUrl="~/NavigateTest2.aspx">Goto NavigateTest2</asp:HyperLink>
HyperLink Control: Rendered HTML
<a id="HyperLink1" href="NavigateTest2.aspx">Goto NavigateTest2</a>
Cross-page posting is frequently desired in a scenario where data is collected on one Web page and processed on another Web page that displays the results. In such a scenario, a Button control typically has its PostBackUrl property set to the Web page to which the processing should post back. The page that receives the PostBack receives the posted data from the first page for processing. This page is referred to as the processing page.
The processing page often needs to access data that was contained inside the initial page that collected the data and delivered the PostBack. The previous page’s data is available inside the Page.PreviousPage property. This property is only set if a cross-page post occurs. If the PreviousPage is set to Nothing (null in C#) no cross-page posting occurred. You can access the controls found in the previous page by using the FindControl method of the PreviousPage property (which is a NamingContainer).
Client-Side Browser Redirect
Often you need to redirect users to another page based on the result of their request or PostBack to the server. The Page.Response object contains the Redirect method for doing just that.
Sometimes you might need to transfer the server-side processing of an entire Web page over to another page. These scenarios are rare and tend to add needless confusion to your code and application. However, you might need to hide the name of the page processing the request from the user. You can do so using the Page.Server.Transfer method. The Transfer method transfers the entire context of a Web page over to another page. The page that receives the transfer generates the response back to the user’s browser. In doing so, the user’s Internet address in his or her browser does not show the result of the transfer. The
User’s address bar still reflects the name of the originally requested page.
Using the Site Map Web Server Control
Thus far you have seen how to help push users from page to page using both client- and server-side techniques. Another key component of any Web site is providing a solid navigational structure for users. Users need to be able to navigate to the various features and functionality provided by your application. ASP.NET provides controls to help you both manage the navigational structure of your site and provide the display of that structure to users.
1. Add a sitemap file to the Web site by right-clicking the project and selecting Add New Item. Select the Site Map item from the Add New Item dialog box. Leave the name of the file as Web.sitemap.
2. Add a set of <siteMapNode> elements to the site map. Each node should represent a page
3. Open an aspx page in Source view. Start by adding an HTML <table> to the page. It should contain two rows. The first row should contain a single column thatspans the table. The second row should contain two columns. Above the table add two SiteMapDataSource controls to the page. You can do so from the Toolbox in the Data section.
Configure one SiteMapDataSource to not show the first node in the source data; name this node sitemapdatasourcemenu. Confi gure the second to show all of the site map data; name this node sitemapdatasourcetree. These controls should look as follows:
4. Add a Menu control to the HTML table’s fi rst row. Configure this control to use the menu data source control. Set its display to show menu items horizontally across the top of your page. Your control’s confi guration might look as follows:
5. Add a TreeView control inside the fi rst column of the second row. Set the DataSourceId attribute accordingly. This column should look as follows:
6. Add a SiteMapPath control to the second column of the second row. Set the Data-SourceId attribute accordingly. This column should look as follows:
7. Finally, add one of the child pages to the site.