Tải bản đầy đủ (.pdf) (8 trang)

Tài liệu Comparing Server and Client Validations docx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (31.19 KB, 8 trang )



Comparing Server and Client Validations
Consider the EmployeeForm.aspx page of the Honest John 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. The employee ID should be a positive integer.
In a Windows Forms application, you would use the Validating event to ensure the user
typed something into the First Name and Last Name text boxes and that the employee ID
value was numeric. Web forms do not have a Validating event, which means that you
cannot use the same approach.
Server Validation
If you examine the TextBox class, you will notice that it publishes the TextChanged
event. This event runs the next time the form is posted back to the server after the user
changes the text typed in the text box. Like all Web Server control events, the
TextChanged event runs at the Web server. This action 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. If the validation being performed is complex, or requires processing that can only
be performed at the Web server (such as ensuring that an Employee ID the user types in
exists in a database) , this might be 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
of the Web server could impose an unacceptable overhead; why not perform this check in
the browser on the client computer and save a network round-trip?
Client Validation
The Web Forms model provides for client-side validation through the use of validation
controls. If the user is running a browser such as Microsoft Internet Explorer 4 or later,
which supports dynamic HTML, these controls generate JavaScript code that runs in the
browser and avoids the need to perform a network round-trip 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 this;


all the browser detection and code generation features are built into the validation
controls. The developer simply drops a validation control onto the Web form, sets its
properties (by using either the Properties window or code), and specifies the validation
rules to be performed and any error messages to be displayed.
There are five types of validation controls supplied with ASP.NET:

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

CompareValidator Use this control to compare the data entered against 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).
NOTE
You should be aware that if a user can type unrestricted text into a text box and
send it to the Web server, they 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 and 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 it 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 2005
Documentation.

CustomValidator Use this control to define your own custom validation logic and
attach it to a control to be validated.
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 into a text box and that this value falls within a particular range, you can attach a
RequiredField Validator 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
RequiredField Validator 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 Range Validator control is useful.
Add RequiredFieldValidator controls
1. In the Microsoft Visual Studio 2005 programming environment, on the File menu,
point to Open, and then click Web Site. In the Open Web Site dialog box,ensure
the File System option is selected, and browse to Microsoft Press\Visual CSharp
Step by Step\Chapter 26\HonestJohn in your My Documents folder. Click Open.
NOTE
You do not need to select a C# solution or project file to open a Web site for
editing; just move to the folder containing the Web site files and sub-folders.
Visual Studio 2005 will generate a new solution file if this folder does not contain
one, and add the Web site files to it. However, this solution file is not essential to
the Web site and you do not need to save it.
NOTE

When you create a new Web site, Visual Studio 2005 creates a solution file in a
solution folder in your My Documents\Visual Studio 2005 folder. If you want to
open a Web site by using the existing solution file rather than generating a new
one, on the File menu point to Open and click Project/Solution, then move to the
solution folder and click the solution file.
2. In the Solution Explorer, right-click EmployeeForm.aspx, and then click Set As
Start Page.
3. Right-click EmployeeForm.aspx again, and then click View Designer to display
the Web form in the Design View window.
4. In the Toolbox, expand the Validation category.
5. Add a RequiredFieldValidator control to the form.
The control appears in the upper left-hand part of the form, displaying the text
“RequiredFieldValidator”. Drag it and position it just below the First Name text
box so it looks like the following graphic. You might need to enable absolute
positioning on the form before you can move the RequiredFieldValidator control
by using the Position item on the Layout menu.

6. With RequiredFieldValidator1 selected, click the Properties window. Set the
ControlTo Validate property to firstName. Type You must type 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 red text on the
form.
7. Add two more RequiredFieldValidator controls to the form. Place the first control
under the Last Name text box, set its ControlToValidate property to lastName, and
type You must type a last name for the employee in its ErrorMessage property.
Resize the control so that the error message appears on a single line if necessary.
Place the second RequiredFieldValidator control under the Employee Id text box;
set its ControlToValidate property to employeeID, and type You must specify an
employee ID in its ErrorMessage property.

8. On the Debug menu, click Start Without Debugging to run the form and test it.
9. When the form first appears in Microsoft Internet Explorer, 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 post-back
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.
10. Type a name in the First Name text box.
As soon as you move away from the text box, the 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 is being sent to the server over the network.
11. 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.
12. Close the form and return to the Visual Studio 2005 programming environment.
Currently, you can type anything into the Employee Id text box. In the following
exercise, you will use a RangeValidator control to restrict the values entered to integers
in the range of 1 through 5000.
Add a RangeValidator control
1. In the Toolbox, add a RangeValidator control to the form and drag it under the
RequiredFieldValidator control below the Employee Id text box. (You might need
to move the Position label and radio buttons down to make space).
2. With the RangeValidator control selected, click the Properties window. Change
the ControlToValidate property to employeeID. Type 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.
3. 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 is displayed.
4. 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 is
displayed.
5. 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.
6. Experiment with other values that are out of range or the wrong type. Try 5001
and the text “AAA” to check that the RangeValidator control works as expected.
7. On the Internet Explorer View menu, click Source.
The HTML source code for the Web form appears in Notepad. Scroll through the
file and examine its contents. Near the end you will find a block of 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.
8. Close the form and return to the Visual Studio 2005 programming environment.
Disabling Client Validation
In the previous 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 your browser. If your browser does not support
JavaScript, all validation checks will be performed by using code running on the Web
server instead.

×