Professional ASP.NET 3.5 in C# and Visual Basic Part 25 pps

10 363 0
Professional ASP.NET 3.5 in C# and Visual Basic Part 25 pps

Đang tải... (xem toàn văn)

Thông tin tài liệu

Evjen c04.tex V2 - 01/28/2008 12:45pm Page 194 Chapter 4: Validation Server Controls As you work through this chapter, you see the different types of validation rules that you can apply to your form elements. Remember that you have no way to validate the truthfulness of the information you collect; instead, you apply rules that respond to such questions as ❑ Is something entered in the text box? ❑ Is the data entered in the text box in the form of an e-mail address? Notice from these questions that you can apply more than a single validation rule to an HTML form element (you’ll see examples of this later in this chapter). In fact, you can apply as many rules to a single element as you want. Applying more rules to elements increases the strictness of the validation applied to the data. Just remember that data collection on the Internet is one of the Internet’s most important features, so you must make sure that the data you collect has value and meaning. You ensure this by eliminating any chance that the information collected does not abide by the rules you outline. Client-Side versus Ser ver-Side Validation If you are new to Web application development, you might not be aware of the difference between client-side and server-side validation. Suppose that the end user clicks the Submit button on a form after filling out some information. What happens in ASP.NET is that this form is packaged in a request and sent to the server where the application resides. At this point in the request/response cycle, you can run validation checks on the information submitted. If you do this, it is called server-side validation because it occurs on the server. On the other hand, it is also possible to supply a script (usually in the form of JavaScript) in the page that is posted to the end user’s browser to perform validations on the data entered in the form before the form is posted back to the originating server. If this is the case, client-side validation has occurred. Both types of validation have their pros and cons. Active Server Pages 2.0/3.0 developers (from the classic ASP days) are quite aware of these pros and cons because they have probably performed all the validation chores themselves. Many developers spent a considerable amount of their classic ASP programming days coding various validation techniques for performance and security. Client-side validation is quick and responsive for the end user. It is something end users expect of the forms that they work with. If something is wrong with the form, using client-side validation ensures that the end user knows this as soon as possible. Client-side validation also pushes the processing power required of validation to the client meaning that you don’t need to spin CPU cycles on the server to process the same information because the client can do the work for you. With this said, client-side validation is the more insecure form of validation. When a page is generated in an end user’s browser, this end user can look at the code of the page quite easily (simply by right-clicking his mouse in the browser and selecting View Code). When he does this, in addition to seeing the HTML code for the page, he can also see all the JavaScript that is associated with the page. If you are validating your form client-side, it doesn’t take much for the crafty hacker to repost a form (containing the values he wants in it) to your server as valid. There are also the cases in which clients have simply disabled the client-scripting capabilities in their browsers — thereby making your validations useless. 194 Evjen c04.tex V2 - 01/28/2008 12:45pm Page 195 Chapter 4: Validation Server Controls Therefore, client-side validation should be considered a convenience and a courtesy to the end user and never as a security mechanism. The more secure form of validation is server-side validation. Server-side validation means that the validation checks are performed on the server instead of on the client. It is more secure because these checks cannot be easily bypassed. Instead, the form data values are checked using server code (C# or VB) on the server. If the form isn’t valid, the page is posted back to the client as invalid. Although it is more secure, server-side validation can be slow. It is sluggish simply because the page has to be posted to a remote location and checked. Your end user might not be the happiest surfer in the world if, after waiting 20 seconds for a form to post, he is told his e-mail address isn’t in the correct format. So what is the correct path? Well, actually, both! The best approach is always to perform client-side validation first and then, after the form passes and is posted to the server, to perform the validation checks again using server-side validation. This approach provides the best of both worlds. It is secure because hackers can’t simply bypass the validation. They may bypass the client-side validation, but they quickly find that their form data is checked once again on the server after it is posted. This vali- dation technique is also highly effective — giving you both the quickness and snappiness of client-side validation. ASP.NET Validation Server Controls In the classic ASP days, developers could spend a great deal of their time dealing with different form validation schemes. For this reason, with the initial release of ASP.NET, the ASP.NET team introduced a series of validation server controls meant to make it a snap to implement sound validation for forms. ASP.NET not only introduces form validations as server controls, but it also makes these controls rather smart. As stated earlier, one of the tasks of classic ASP developers was to determine where to perform form validation — either on the client or on the server. The ASP.NET validation server controls eliminate this dilemma because ASP.NET performs browser detection when generating the ASP.NET page and makes decisions based on the information it gleans. This means that if the browser can support the JavaScript that ASP.NET can send its way, the validation occurs on the client-side. If the client cannot support the JavaScript meant for client-side validation, this JavaScript is omitted and the validation occurs on the server. The best part about this scenario is that even if client-side validation is initiated on a page, ASP.NET still performs the server-side validation when it receives the submitted page, thereby ensuring security won’t be compromised. This decisive nature of the validation server controls means that you can build your ASP.NET Web pages to be the best they can possibly be — rather than dumbing-down your Web applications for the lowest common denominator. Presently, six validation controls are available to you in ASP.NET 3.5. No new validation server controls have been added to ASP.NET since the initial release of the technology, but ASP.NET 2.0 introduced some new features, such as validation groups and new JavaScript capabilities. Both these features are discussed in this chapter. The available validation server controls include ❑ RequiredFieldValidator ❑ CompareValidator 195 Evjen c04.tex V2 - 01/28/2008 12:45pm Page 196 Chapter 4: Validation Server Controls ❑ RangeValidator ❑ RegularExpressionValidator ❑ CustomValidator ❑ ValidationSummary Working with ASP.NET validation server controls is no different from working with any other ASP.NET server control. Each of these controls allows you to drag and drop it onto a design surface or to work with it directly from the code of your ASP.NET page. These controls can also be modified so that they appear exactly as you wish — ensuring the visual uniqueness that your applications might require. You see some aspects of this throughout this chapter. If the ASP.NET Validation controls don’t meet your needs, you can certainly write your own custom validation controls. However, there are third-party controls available such as Peter Blum’s Validation and More (VAM) from www.peterblum.com/VAM , which includes over 40 ASP.NET validation controls. The following table describes the functionality of each of the available validation server controls. Validation Server C ontrol Description RequiredFieldValidator Ensures that the user does not skip a form entry field. CompareValidator Allows for comparisons between the user’s input and another item using a comparison operator (equals, greater than, less than, and so on). RangeValidator Checks the user’s input based upon a lower- and upper-level range of numbers or characters. RegularExpressionValidator Checks that the user’s entry matches a pattern defined by a regular expression. This is a good control to use to check e-mail addresses and phone numbers. CustomValidator Checks the user’s entry using custom-coded validation logic. ValidationSummary Displays all the error messages from the validators in one specific spot on the page. Validation Causes Validation doesn’t just happen; it occurs in response to an event. In most cases, it is a button click event. The Button, LinkButton, and ImageButton server controls all have the capability to cause a page’s form validation to initiate. This is the default behavior. Dragging and dropping a Button server control onto your form will give you the following initial result: < asp:Button ID="Button1" Runat="server" Text="Button" / > 196 Evjen c04.tex V2 - 01/28/2008 12:45pm Page 197 Chapter 4: Validation Server Controls If you look through the properties of the Button control, you can see that the CausesValidation property is set to True . As stated, this is the default behavior — all buttons on the page, no matter how many there are, cause the form validation to fire. If you have multiple buttons on an ASP.NET page, and you don’t want each and every button to initiate the form validation, you can set the CausesValidation property to False for all the buttons you want to ignore the validation process (for example, a form’s Cancel button): < asp:Button ID="Button1" Runat="server" Text="Cancel" CausesValidation="False" / > The RequiredFieldValidator Server Control The RequiredFieldValidator control simply checks to see if something was entered into the HTML form element. It is a simple validation control, but it is one of the most frequently used. You must have a RequiredFieldValidator control for each form element on which you wish to enforce a value-required rule. Listing 4-1 shows a simple use of the RequiredFieldValidator control. Listing 4-1: A simple use of the RequiredFieldValidator server control VB < %@ Page Language="VB" % > < script runat="server" > Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) If Page.IsValid Then Label1.Text = "Page is valid!" End If End Sub < /script > < html xmlns="http://www.w3.org/1999/xhtml" > < head runat="server" > < title > RequiredFieldValidator < /title > < /head > < body > < form id="form1" runat="server" > < div > < asp:TextBox ID="TextBox1" Runat="server" >< /asp:TextBox > < asp:RequiredFieldValidator ID="RequiredFieldValidator1" Runat="server" Text="Required!" ControlToValidate="TextBox1" > < /asp:RequiredFieldValidator > < br / > < asp:Button ID="Button1" Runat="server" Text="Submit" OnClick="Button1_Click" / > < br / > < br / > < asp:Label ID="Label1" Runat="server" >< /asp:Label > Continued 197 Evjen c04.tex V2 - 01/28/2008 12:45pm Page 198 Chapter 4: Validation Server Controls < /div > < /form > < /body > < /html > C# < %@ Page Language="C#" % > < script runat="server" > protected void Button1_Click(Object sender, EventArgs e) { if (Page.IsValid) { Label1.Text = "Page is valid!"; } } < /script > Build and run this page. You are then presented with a simple text box and button on the page. Don’t enter any value inside the text box, and click the Submit button. The result is shown in Figure 4-1. Figure 4-1 Now look at the code from this example. First, nothing is different about the TextBox, Button, or Label controls. They are constructed just as they would be if you were not using any type of form validation. This page does contain a simple RequiredFieldValidator control, however. Several properties of this control are especially notable because you will use them in most of the validation server controls you create. The first property to look at is the Text property. This property is the value that is shown to the end user via the Web page if the validation fails. In this case, it is a simple Required! string. The second property to look at is the ControlToValidate property. This property is used to make an association between this validation server control and the ASP.NET form element that requires the validation. In this case, the value specifies the only element in the form — the text box. As you can see from this example, the error message is constructed from an attribute within the < asp:RequiredFieldValidator > control. You can also accomplish this same task by using the Text attribute, as shown in Listing 4-2. 198 Evjen c04.tex V2 - 01/28/2008 12:45pm Page 199 Chapter 4: Validation Server Controls Listing 4-2: Using the Text attribute < asp:RequiredFieldValidator ID="RequiredFieldValidator1" Runat="server" Text="Required!" ControlToValidate="TextBox1" > < /asp:RequiredFieldValidator > You can also express this error message between the < asp:RequiredFieldValidator > opening and closing nodes, as shown in Listing 4-3. Listing 4-3: Placing values between nodes < asp:RequiredFieldValidator ID="RequiredFieldValidator1" Runat="server" ControlToValidate="TextBox1" > Required! < /asp:RequiredFieldValidator > Looking at the Results Generated Again, the RequiredFieldValidator control uses client-side validation if the browser allows for such an action. You can see the client-side validation for yourself (if your browser allows for this) by right-clicking on the page and selecting View Source from the menu. In the page code, you see the JavaScript shown in Listing 4-4. Listing 4-4: The generated JavaScript page markup removed for clarity here < script type="text/javascript" > < ! function WebForm_OnSubmit() { if (ValidatorOnSubmit() == false) return false; return true; } // > < /script > page markup removed for clarity here < script type="text/javascript" > < ! var Page_Validators = new Array(document.getElementById("RequiredFieldValidator1"));// > < /script > < script type="text/javascript" > < ! var RequiredFieldValidator1 = document.all ? document.all["RequiredFieldValidator1"] : document.getElementById("RequiredFieldValidator1"); Continued 199 Evjen c04.tex V2 - 01/28/2008 12:45pm Page 200 Chapter 4: Validation Server Controls RequiredFieldValidator1.controltovalidate = "TextBox1"; RequiredFieldValidator1.text = "Required!"; RequiredFieldValidator1.evaluationfunction = "RequiredFieldValidatorEvaluateIsValid"; RequiredFieldValidator1.initialvalue = ""; // > < /script > page markup removed for clarity here < script type="text/javascript" > < ! var Page_ValidationActive = false; if (typeof(ValidatorOnLoad) == "function") { ValidatorOnLoad(); } function ValidatorOnSubmit() { if (Page_ValidationActive) { return ValidatorCommonOnSubmit(); } else { return true; } } // > < /script > In the page code, you may also notice some changes to the form elements (the former server controls) that deal with the submission of the form and the associated validation requirements. Using the InitialValue Property Another important property when working with the RequireFieldValidator control is the Initial- Value property. Sometimes you have form elements that are populated with some default properties (for example, from a data store), and these form elements might present the end user with values that require changes before the form can be submitted to the server. When using the InitialValue property, you specify to the RequiredFieldValidator control the initial text of the element. The end user is then required to change that text value before he can submit the form. Listing 4-5 shows an example of using this property. Listing 4-5: Working with the InitialValue property < asp:TextBox ID="TextBox1" Runat="server" > My Initial Value < /asp:TextBox > &nbsp; < asp:RequiredFieldValidator ID="RequiredFieldValidator1" Runat="server" Text="Please change the value of the textbox!" ControlToValidate="TextBox1" InitialValue="My Initial Value" > < /asp:RequiredFieldValidator > 200 Evjen c04.tex V2 - 01/28/2008 12:45pm Page 201 Chapter 4: Validation Server Controls In this case, you can see that the InitialValue property contains a value of My Initial Value .When the page is built and run, the text box contains this value as well. The RequiredFieldValidator control requires a change in this value for the page to be considered valid. Disallowing Blank Entries and Requiring Changes at the Same T ime In the preceding example of the use of the InitialValue property, an interesting problem arises. First, if you run the associated example, one thing the end user can do to get past the form validation is to submit the page with no value entered in this particular text box. A blank text box does not fire a validation error because the RequiredFieldValidator control is now reconstructed to force the end user only to change the default value of the text box (which he did when he removed the old value). When you reconstruct the RequiredFieldValidator control in this manner, nothing in the validation rule requires that something be entered in the text box — just that the initial value be changed. It is possible for the user to completely bypass the form validation process by just removing anything entered in this text box. There is a way around this, however, and it goes back to what we were saying earlier about how a form is made up of multiple validation rules — some of which are assigned to the same form element. To both require a change to the initial value of the text box and to disallow a blank entry (thereby mak- ing the element a required element), you must put an additional RequiredFieldValidator control on the page. This second RequiredFieldValidator control is associated with the same text box as the first RequiredFieldValidator control. This is illustrated in the example shown in Listing 4-6. Listing 4-6: Using two RequiredFieldValidator controls for one form element < asp:TextBox ID="TextBox1" Runat="server" > My Initial Value < /asp:TextBox > &nbsp; < asp:RequiredFieldValidator ID="RequiredFieldValidator1" Runat="server" Text="Please change value" ControlToValidate="TextBox1" InitialValue="My Initial Value" >< /asp:RequiredFieldValidator > < asp:RequiredFieldValidator ID="RequiredFieldValidator2" Runat="server" Text="Do not leave empty" ControlToValidate="TextBox1" > < /asp:RequiredFieldValidator > In this example, you can see that the text box does indeed have two RequiredFieldValidator controls associated with it. The first, RequiredFieldValidator1 , requires a change to the default value of the text box through the use of the InitialValue property. The second RequiredFieldValidator control, RequiredFieldValidator2 , simply makes the TextBox1 control a form element that requires a value. You get the behavior you want by applying two validation rules to a single form element. Validating Drop-Down Lists with the RequiredFieldValidator Control So far, you have seen a lot of examples of using the RequiredFieldValidator control with a series of text boxes, but you can just as easily use this validation control with other form elements as well. For example, you can use the RequiredFieldValidator control with an < asp:DropDownList > server control. To see this, suppose that you have a drop-down list that requires the end user to select her profession from a list of items. The first line of the drop-down list includes instructions to the end user about what to select, and you want to make this a required form element as well. The code to do this is shown in Listing 4-7. 201 Evjen c04.tex V2 - 01/28/2008 12:45pm Page 202 Chapter 4: Validation Server Controls Listing 4-7: Drop-down list validations < asp:DropDownList id="DropDownList1" runat="server" > < asp:ListItem Selected="True" > Select a profession < /asp:ListItem > < asp:ListItem > Programmer < /asp:ListItem > < asp:ListItem > Lawyer < /asp:ListItem > < asp:ListItem > Doctor < /asp:ListItem > < asp:ListItem > Artist < /asp:ListItem > < /asp:DropDownList > &nbsp; < asp:RequiredFieldValidator id="RequiredFieldValidator1" runat="server" Text="Please make a selection" ControlToValidate="DropDownList1" InitialValue="Select a profession" > < /asp:RequiredFieldValidator > Just as when you work with the text box, the RequiredFieldValidator control in this example associates itself with the DropDownList control using the ControlToValidate property. The drop-down list to which the validation control is bound has an initial value — Select a profession . You obviously don’t want your end user to retain that value when she posts the form back to the server. So again, you use the InitialValue property of the RequiredFieldValidator control. The value of this property is assigned to the initial selected value of the drop-down list. This forces the end user to select one of the provided professions in the drop-down list before she is able to post the form. The CompareValidator Server Control The CompareValidator control allows you to make comparisons between two form elements as well as to compare values contained within form elements to constants that you specify. For instance, you can specify that a form element’s value must be an integer and greater than a specified number. You can also state that values must be strings, dates, or other data types that are at your disposal. Validating Against Other Controls One of the more common ways of using the CompareValidator control is to make a comparison between two form elements. For example, suppose that you have an application that requires users to have pass- words in order to access the site. You create one text box asking for the user’s password and a second text box that asks the user to confirm the password. Because the text box is in password mode, the end user cannot see what she is typing — just the number of characters that she has typed. To reduce the chances of the end user mistyping her password and inputting this incorrect password into the system, you ask her to confirm the password. After the form is input into the system, you simply have to make a com- parison between the two text boxes to see if they match. If they match, it is likely that the end user typed the password correctly, and you can input the password choice into the system. If the two text boxes do not match, you want the form to be invalid. The following example, in Listing 4-8, demonstrates this situation. Listing 4-8: Using the CompareValidator to test values against other control v alues VB < %@ Page Language="VB" % > < script runat="server" > 202 Evjen c04.tex V2 - 01/28/2008 12:45pm Page 203 Chapter 4: Validation Server Controls Protected Sub Button1_Click(sender As Object, e As EventArgs) If Page.IsValid Then Label1.Text = "Passwords match" End If End Sub < /script > < html xmlns="http://www.w3.org/1999/xhtml" > < head runat="server" > < title > CompareFieldValidator < /title > < /head > < body > < form runat="server" id="Form1" > < p > Password < br > < asp:TextBox ID="TextBox1" Runat="server" TextMode="Password" >< /asp:TextBox > &nbsp; < asp:CompareValidator ID="CompareValidator1" Runat="server" Text="Passwords do not match!" ControlToValidate="TextBox2" ControlToCompare="TextBox1" >< /asp:CompareValidator > < /p > < p > Confirm Password < br > < asp:TextBox ID="TextBox2" Runat="server" TextMode="Password" >< /asp:TextBox > < /p > < p > < asp:Button ID="Button1" OnClick="Button1_Click" Runat="server" Text="Login" >< /asp:Button > < /p > < p > < asp:Label ID="Label1" Runat="server" >< /asp:Label > < /p > < /form > < /body > < /html > C# < %@ Page Language="C#" % > < script runat="server" > protected void Button1_Click(Object sender, EventArgs e) { if (Page.IsValid) Label1.Text = "Passwords match"; } < /script > Looking at the CompareValidator control on the form, you can see that it is similar to the Required- FieldValidator control. The CompareValidator control has a property called ControlToValidate that 203 . ControlToValidate="TextBox1" > < /asp: RequiredFieldValidator > You can also express this error message between the < asp: RequiredFieldValidator > opening and closing nodes, as shown in Listing 4 -3. Listing 4 -3: Placing. server controls have been added to ASP. NET since the initial release of the technology, but ASP. NET 2.0 introduced some new features, such as validation groups and new JavaScript capabilities Controls In the classic ASP days, developers could spend a great deal of their time dealing with different form validation schemes. For this reason, with the initial release of ASP. NET, the ASP. NET

Ngày đăng: 05/07/2014, 18:20

Từ khóa liên quan

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan