Additional Resources | Contents
INPUT VALIDATIONA 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 PageValidation 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 ErrorsYou 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 GroupsOften 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 ClassThe 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 ControlThe 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 ControlYou 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 ValidationTo 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.
SITE NAVIGATIONChoosing a Method to Navigate Pages- Client-side navigation Client-side code or markup allows a user to request a new Web page. Your client code or markup requests a new Web page in response to a client-side event, such as clicking a hyperlink or executing JavaScript as part of a button click. - 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. Client-Side NavigationHyperLink Control: Source <asp:HyperLink ID="HyperLink1" runat="server"
NavigateUrl="~/NavigateTest2.aspx">Goto
NavigateTest2</asp:HyperLink> HyperLink Control: Rendered HTML <a id="HyperLink1"
href="NavigateTest2.aspx">Goto NavigateTest2</a> Cross-Page PostingThe 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
Server-Side TransferUser’s address bar still reflects the name of the originally requested page.
Using the Site Map Web Server ControlThus 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. 7. Finally, add one of the child pages to the site.
|