Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
C# 2008 Step by Step.pdf
Скачиваний:
26
Добавлен:
25.03.2016
Размер:
13.96 Mб
Скачать

Chapter 28

Understanding Web Forms

Validation Controls

After completing this chapter, you will be able to:

Validate user input in a Microsoft ASP.NET Web form by using the ASP.NET validation controls.

Determine whether to perform user input validation in the user's Web browser or at the Web server.

As with a Microsoft Windows Presentation Foundation (WPF) application, validating user input is an important part of any Web application. With WPF, you can check that the user’s input makes sense by binding controls to properties of business objects and letting the code in these business objects validate the data, or by writing code to validate the contents of these fields in response to events that occur when the user moves from field to field on a form. ASP.NET Web forms do not support binding to business objects for validation purposes, so at first glance it appears that your only option might be to use events. However, there is one fundamental consideration that you should think about. Web applications are distributed in their nature: the presentation logic runs in the Web browser on the user's computer, while the code for the application runs on the Web server. With this in mind, should you perform user input validation at the client (the Web browser) or at the Web server? In this chapter, you will examine this question and discover the options that are available to you.

Note As you read this chapter, you might be surprised to discover that it contains no C# code. This is intentional. You could validate data by using C# methods, but sometimes it is equally instructive to see situations where you do not actually need to write C# code to perform potentially complex tasks.

Comparing Server and Client Validations

Consider the EmployeeForm.aspx page of the Litware Web site again. The user is expected to enter the details of an employee: name, employee ID, position, and role. All the text boxes should be mandatory. Additionally, the employee ID should be a positive integer.

587

588 Part VI Building Web Applications

Validating Data at the Web Server

If you examine the TextBox class, you will notice that it provides the TextChanged event. After

the user changes the text in the text box, this event runs the next time the form is posted back to the server. As with all Web Server control events, the TextChanged event handler

runs at the Web server. Validating data at the server involves transmitting data from the Web browser to the server, processing the event at the server to validate the data, and then packaging up any validation errors as part of the HTML response sent back to the client so that the browser can display these errors. If the validation being performed is complex or requires processing that can be performed only at the Web server (such as ensuring that an employee ID the user enters exists in a database), this is an acceptable technique. But if you are simply inspecting the data in a single text box in isolation (such as making sure that the user types a positive integer into an Employee ID text box), performing this type of validation on the Web server could impose unacceptable overhead; why not perform this check in the browser on the client computer and save a network round-trip?

Validating Data in the Web Browser

The ASP.NET Web Forms model facilitates performing client-side validation in a Web browser through the use of validation controls. If the user is running a browser (such as Microsoft Internet Explorer 4 or later) that supports dynamic HTML, the validation controls generate JavaScript code that runs in the browser and avoids the need to perform a network roundtrip to the server. If the user is running an older browser, the validation controls generate server-side code instead. The key point is that the developer creating the Web form does not have to worry about checking for browser capabilities; all the browser detection and code generation features are built into the ASP.NET validation controls. The developer simply

drops an ASP.NET validation control onto the Web form, sets its properties (either by using the Properties window or by writing code), and specifies the validation rules to be performed

and any error messages to be displayed.

ASP.NET provides the following validation controls:

RequiredFieldValidator Use this control to ensure that the user has entered data into a control.

CompareValidator Use this control to compare the data entered with a constant value, the value of a property of another control, or a value retrieved from a database.

RangeValidator Use this control to check the data entered by a user against a range of values, checking that the data falls either inside or outside a given range.

RegularExpressionValidator Use this control to check that the data input by the user matches a specified regular expression, pattern, or format (such as a telephone number, for example).

Chapter 28 Understanding Web Forms Validation Controls

589

CustomValidator Use this control to define your own custom validation logic and attach it to a control to be validated.

Note You should be aware that if a user can type unrestricted text into a text box and send it to the Web server, the user could type text that looks like HTML tags (<b> for example). Hackers sometimes use this technique to inject HTML into a client request in an attempt to cause damage to the Web server or to try to break in. (I am not going to go into the details here!) By default, if you try this trick with an ASP.NET Web page, the request will be aborted and the user is shown the message “A potentially dangerous Request.Form value was detected from the client.” You can

disable this check, although that is not recommended. A better approach is to use a RegularExpressionValidator control to verify that the user input in a text box does not constitute

an HTML tag (or anything that looks like it). For more information about regular expressions and how to use them, see the topic “.NET Framework Regular Expressions” in the Microsoft Visual Studio 2008 documentation.

Although each control performs a single well-defined type of validation, you can use several

of them in combination. For example, if you want to ensure that the user enters a value in a text box and that this value falls in a particular range, you can attach a RequiredFieldValidator control and a RangeValidator control to the text box.

These controls can work in conjunction with a ValidationSummary control to display error messages. You will use some of these controls in the following exercises.

Implementing Client Validation

Returning to the EmployeeForm.aspx Web form, you can probably see that

RequiredFieldValidator controls will be required for the First Name, Last Name, and Employee Id text boxes. The employee ID must also be numeric and should be a positive integer. In this

application, you will specify that the employee ID must be between 1 and 5000. This is where a RangeValidator control is useful.

Add RequiredFieldValidator controls

1.Start Microsoft Visual Studio 2008 if it is not already running.

2.If you are using Visual Studio 2008 Professional Edition or Enterprise Edition, on the File menu, point to Open, and then click Web Site.

3.If you are using Microsoft Visual Web Developer 2008 Express Edition, on the File menu, click Open Web Site.

4.In the Open Web Site dialog box, ensure that the File System option is selected,

browse to Microsoft Press\Visual CSharp Step by Step\Chapter 28\Litware under your Documents folder, and then click Open.

590

Part VI Building Web Applications

Note When you create a new Web site, Visual Studio 2008 creates a solution file in a solution folder in the Visual Studio 2008 folder under your Documents folder. However, you do not need to select a Microsoft Visual C# solution or project file to open a Web site

for editing; just move to the folder containing the Web site files and subfolders. If you do want to open a Web site by using the solution file, on the File menu, point to Open, and click Project/Solution (instead of Web Site), move to the solution folder, and then click the

solution file.

5.In Solution Explorer, right-click EmployeeForm.aspx, and then click Set As Start Page.

6.Right-click EmployeeForm.aspx again, and then click View Designer to display the Web form in the Design View window.

7.In the Toolbox, expand the Validation category.

8.Add a RequiredFieldValidator control to the form.

The control appears in the upper-left part of the form, displaying the text “RequiredFieldValidator”.

9.Click the Source button to display the HTML source code for the form. Locate the code for the RequiredFieldValidator control toward the bottom of the file, and set the Style property to position it underneath the firstName text box, as shown here in bold type. (The position of a validation control determines where the error message is displayed.)

<asp:RequiredFieldValidator ID=”RequiredFieldValidator1”...

Style=”position: absolute; left: 166px; top: 128px”></asp:RequiredFieldValidator>

10.Click the Design button, and then select the RequiredFieldValidator control. In the Properties window, use the drop-down list to set the ControlToValidate property to firstName. Setting the ControlToValidate property links the validation control to the item it will validate. Enter You must specify a first name for the employee in the

ErrorMessage property. This is the message that will be displayed if the control to be validated (the First Name text box) is left blank. Notice that this message replaces the default red text error message (“RequiredFieldValidator”) on the form.

11.Add two more RequiredFieldValidator controls to the form.

12.Click the Source button, and add the Style properties shown here in bold type to position these controls under the lastName and employeeID text boxes.

<asp:RequiredFieldValidator ID=”RequiredFieldValidator2”...

Style=”position: absolute; left: 508px; top: 128px”></asp:RequiredFieldValidator>

<asp:RequiredFieldValidator ID=”RequiredFieldValidator3”...

Style=”position: absolute; left: 166px; top: 194px”></asp:RequiredFieldValidator>

13.Click the Design button, and then select the RequiredFieldValidator control under the Last Name text box. Using the Properties window, set its ControlToValidate property to lastName, and enter You must specify a last name for the employee in its

ErrorMessage property. Notice that the RequiredFieldValidator control automatically resizes itself to display the complete error message.

Chapter 28 Understanding Web Forms Validation Controls

591

14.Select the RequiredFieldValidator control under the Employee Id text box; set its

ControlToValidate property to employeeID, and enter You must specify an employee ID in its ErrorMessage property.

15.On the Debug menu, click Start Without Debugging to run the form in Windows Internet Explorer.

16.When the form first appears, all the required text boxes will be empty. Click Save. The error messages belonging to all three RequiredFieldValidator controls are displayed.

Notice that the Click event for the Save button did not run, and the label at the bottom of the form did not display the data summary (and the screen did not even flicker). This behavior is because the validation controls prevented the postback to the server; they generate code that can be executed by the browser, and they will continue to block posts back to the server until all the errors have been corrected.

Note If you click the Clear button while an error message is displayed, it will not clear the form because the error blocks the postback to the Web server. ASP.NET provides support for client-side scripting so that you can add JavaScript code to clear the Web form. This code is not blocked by postbacks because it runs in the user’s Web browser (assuming the browser supports JavaScript). The validation controls actually generate JavaScript code that runs in the user’s browser rather than being posted back to the Web server. The details of writing your own client-side JavaScript code in an ASP.NET Web form are outside the scope of this book, but for more information, search for the article “How to Add Client Script Events to ASP.NET Web Server Controls” in the documentation provided with Visual Studio 2008.

17. Type a name in the First Name text box.

592

Part VI Building Web Applications

As soon as you move away from the text box, the corresponding error message disappears. If you return to the First Name text box, erase the contents, and then move

to the next text box, the error message is displayed again. All this functionality is being performed in the browser with no data being sent to the server over the network.

18.Enter values in the First Name, Last Name, and Employee Id text boxes, and then click

Save.

This time the Click event runs and the summary is displayed in the InfoLabel control at the bottom of the form.

19.Close the form, and return to Visual Studio 2008.

Currently, you can type anything into the Employee Id text box. In the following exercise, you will use a RangeValidator control to restrict the acceptable values to integers in the range of 1

through 5000.

Add a RangeValidator control

1.In the Design View window, from the Toolbox, add a RangeValidator control to the form.

2.Click the Source button, and add the Style properties shown here in bold type to position the RangeValidator control under the employeeID text box.

<asp:RangeValidator ID=”RangeValidator1”...

Style=”position: absolute; left: 166px; top: 194px”></asp:RangeValidator>

This is exactly the same position as the RequiredFieldValidator control for the employeeID text box. Specifying the same location for these two error messages is not

a problem because the validations performed by these controls are mutually exclusive (if the employee ID is blank, the RangeValidator control cannot test the value entered

by the user), so only one of the error messages can be displayed.

3.Click anywhere in the HTML code for the RangeValidator1 control. In the Properties window, set the ControlToValidate property to employeeID. Enter The employee ID must be between 1 and 5000 in the ErrorMessage property. Set the MaximumValue property to 5000, the MinimumValue property to 1, and the Type property to Integer.

Note You can use the RangeValidator control to restrict the range of non-numeric data by setting the Type property. The types you can specify are String, Integer, Double, Date, and Currency. You should specify values of the appropriate type for the MaximumValue and MinimumValue properties. The RangeValidator control uses the collation sequence of

the character set used by the current locale when performing range checking for strings, and when checking Date ranges, an earlier date is considered to be lower than a later date.

4.Run the form again. Enter a first name and a last name, but leave the employee ID blank. Click Save.

An error message telling you that you must supply an employee ID appears.

Chapter 28 Understanding Web Forms Validation Controls

593

5.Type –1 in the Employee Id text box, and then click Save.

An error message telling you that the employee ID must be between 1 and 5000 appears.

6.Type 101 in the Employee Id text box, and then click Save.

This time the data is valid. The form is posted back to the server, the Click event of the Save button runs, and a summary of the information entered in the InfoLabel label appears at the bottom of the form.

7.Experiment with other values that are out of range or of the wrong type. Try 5001 and the text “AAA” to check that the RangeValidator control works as expected.

8.On the Internet Explorer toolbar, click the Page drop-down list, and then click View Source to display the source of the HTML page being displayed in the browser.

Note If the Internet Explorer Security message box appears, click Allow so that you can view the source file for the page.

Notepad starts and displays the HTML source for the page. Scroll through the file and examine its contents. Near the end, you will find some JavaScript code that performs the validations. This code was generated by using the properties of the validation controls. Close Notepad when you have finished browsing the HTML source code.

9. Close Internet Explorer, and return to Visual Studio 2008.

Disabling Client-Side Validation

In the preceding exercise, you saw that the validations were performed by using JavaScript code running in the browser. The ASP.NET runtime generates this code automatically, depending on the capabilities of the Web browser being used to view the page. If the browser does not support JavaScript, all validation checks will be performed by using code running on the Web server instead. The validation will

be performed only when the form is posted back to the server.

If you want, you can suppress client-side validation and force all checks to be performed at the server. To do this, set the EnableClientScript property of the validation

control to False. You might find it useful to do this under certain circumstances, such as those involving custom validations (by using the CustomValidator control) that are complex or require access to data that is available only on the server. The CustomValidator control also has a ServerValidate event that can be used to perform additional validation explicitly on the server, even if EnableClientScript is set to True.

594 Part VI Building Web Applications

You have seen how validation controls can validate the data that the user enters, but

the error message display is not very pretty. In the following exercise, you will use a ValidationSummary control to change the way that the error information is presented to

the user.

Add a ValidationSummary control

1.In the Code and Text Editor window, click anywhere in the HTML code for the

RequiredFieldValidator1 control. In the Properties window, set the Text property to *.

If you set the Text property of a validation control, the corresponding text value is

displayed on the form rather than the error message. (If no value is specified for the Text property, the value of the ErrorMessage property is displayed.)

2.Modify the Style property of the RequiredFieldValidator1 control to position it to the right of the First Name text box, as shown in bold type here:

<asp:RequiredFieldValidator ID=”RequiredFieldValidator1” ...

Style=”position: absolute; left: 400px; top: 106px”></asp:RequiredFieldValidator>

Now, if a validation error occurs, the user will see a red asterisk appear next to the text box with the error.

3.Click anywhere in the HTML code for the RequiredFieldValidator2 control, set its Text property to *, and then change the Style to move it to the right of the Last Name text box.

<asp:RequiredFieldValidator ID=”RequiredFieldValidator2” ...

Style=”position: absolute; left: 744px; top: 106px”></asp:RequiredFieldValidator>

4.Click anywhere in the HTML code for the RequiredFieldValidator3 control, set its Text property to *, and then change the Style property to move it to the right of the

Employee Id text box.

<asp:RequiredFieldValidator ID=”RequiredFieldValidator3” ...

Style=”position: absolute; left: 400px; top: 172px”></asp:RequiredFieldValidator>

5.Click anywhere in the HTML code for the RangeValidator1 control, set its Text property to *, and then change the Style property to move it to the right of the Employee Id text box.

<asp:RangeValidator ID=”RangeValidator1” ...

Style=”position: absolute; left: 400px; top: 172px”></asp:RangeValidator>

6.Click the Design button. From the Toolbox, add a ValidationSummary control to the form.

7.Click the Source button, locate the ValidationSummary control toward the end of the file, and add the following Style property to place it in the space above the button controls and to the right of the radio buttons.

Chapter 28 Understanding Web Forms Validation Controls

595

<asp:ValidationSummary ID=”ValidationSummary1” ...

Style=”position: absolute; left: 300px; top: 260px” />

A ValidationSummary control displays the ErrorMessage values for all of the validation controls on the Web form.

8.In the Properties window, verify that the ShowSummary property for the

ValidationSummary1 control is set to True.

9.Run the Web form. When the form appears in Internet Explorer, leave the First Name, Last Name, and Employee Id text boxes blank, and then click Save.

Red asterisks appear next to each of the text boxes, and the corresponding error messages are displayed in the ValidationSummary control at the bottom of the form.

10.Enter a first name and a last name, and then type AAA in the Employee Id text box.

As you move from text box to text box, the asterisks disappear from the First Name and Last Name text boxes, but an asterisk remains next to the Employee Id text box.

11.Click Save.

The error message displayed by the ValidationSummary control changes.

12.Type 101 in the Employee Id text box, and then click Save.

All error messages and asterisks disappear, and a summary of the data you entered appears in the InfoLabel control as before.

13.Close the form, and return to Visual Studio 2008.

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]