Professional ASP.NET 3.5 in C# and Visual Basic Part 26 pdf

10 315 0
Professional ASP.NET 3.5 in C# and Visual Basic Part 26 pdf

Đ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 204 Chapter 4: Validation Server Controls associates itself with one of the form elements on the page. In this case, you need only a single CompareValidator control on the page because a single comparison is made. In this example, you are making a comparison between the value of TextBox2 and that of TextBox1 . Therefore, you use the ControlToCompare property. This specifies what value is compared to TextBox2 . In this case, the value is TextBox1 . It’s as simple as that. If the two text boxes do not match after the page is posted by the end user, the value of the Text property from the CompareValidator control is displayed in the browser. An example of this is shown in Figure 4-2. Figure 4-2 Validating Against Constants Besides being able to validate values against values in other controls, you can also use the Compare Validator control to make comparisons against constants of specific data types. For example, suppose you have a text box on your registration form that asks for the age of the user. In most cases, you want to get back an actual number and not something such as aa or bb as a value. Listing 4-9 shows you how to ensure that you get back an actual number. Listing 4-9: Using the CompareValidator to validate against constants Age: < asp:TextBox ID="TextBox1" Runat="server" MaxLength="3" > < /asp:TextBox > &nbsp; < asp:CompareValidator ID="CompareValidator1" Runat="server" Text="You must enter a number" ControlToValidate="TextBox1" Type="Integer" Operator="DataTypeCheck" >< /asp:CompareValidator > 204 Evjen c04.tex V2 - 01/28/2008 12:45pm Page 205 Chapter 4: Validation Server Controls In this example, the end user is required to enter in a number into the text box. If she attempts to bypass the validation by entering a fake value that contains anything other than a number, the page is identified as invalid, and the CompareValidator control displays the value of the Text property. To specify the data types that you want to use in these comparisons, you simply use the Type property. The Type property can take the following values: ❑ Currency ❑ Date ❑ Double ❑ Integer ❑ String Not only can you make sure that what is entered is of a specific data type, but you can also make sure that what is entered is valid when compared to specific constants. For instance, you can make sure what is entered in a form element is greater than, less than, equal to, greater than or equal to, or less than or equal to a specified value. An example of this is illustrated in Listing 4-10. Listing 4-10: Making comparisons with the CompareValidator control Age: < asp:TextBox ID="TextBox1" Runat="server" >< /asp:TextBox > &nbsp; < asp:CompareValidator ID="CompareValidator1" Runat="server" Operator="GreaterThan" ValueToCompare="18" ControlToValidate="TextBox1" Text="You must be older than 18 to join" Type="Integer" > < /asp:CompareValidator > In this case, the CompareValidator control not only associates itself with the TextBox1 control and requires that the value must be an integer, but it also uses the Operator and the ValueToCompare prop- erties to ensure that the number is greater than 18. Therefore, if the end user enters a value of 18 or less, the validation fails, and the page is considered invalid. The Operator property can take one of the following values: ❑ Equal ❑ NotEqual ❑ GreaterThan ❑ GreaterThanEqual ❑ LessThan ❑ LessThanEqual ❑ DataTypeCheck 205 Evjen c04.tex V2 - 01/28/2008 12:45pm Page 206 Chapter 4: Validation Server Controls The ValueToCompare property is where you place the constant value used in the comparison. In the preceding example, it is the number 18 . The RangeValidator Server Control The RangeValidator control is quite similar to that of the CompareValidator control, but it makes sure that the end-user value or selection provided is between a specified range as opposed to being just greater than or less than a specified constant. For an example of this, go back to the text-box element that asks for the age of the end user and performs a validation on the value provided. This is illustrated in Listing 4-11. Listing 4-11: Using the RangeValidator control to test an integer value Age: < asp:TextBox ID="TextBox1" Runat="server" >< /asp:TextBox > &nbsp; < asp:RangeValidator ID="RangeValidator1" Runat="server" ControlToValidate="TextBox1" Type="Integer" Text="You must be between 30 and 40" MaximumValue="40" MinimumValue="30" >< /asp:RangeValidator > In this example, this page consists of a text box asking for the age of the end user. The RangeValidator control makes an analysis of the value provided and makes sure the value is somewhere in the range of 30 to 40. This is done using the MaximumValue and MinimumValue properties. The RangeValidator control also makes sure what is entered is an integer data type. It uses the Type property, which is set to Integer . The collection of screenshots in Figure 4-3 shows this example in action. Figure 4-3 206 Evjen c04.tex V2 - 01/28/2008 12:45pm Page 207 Chapter 4: Validation Server Controls As you can see from the screenshots in Figure 4-3, a value of less than 30 causes the RangeValidator control to fire, as does a number greater than 40. A value that is somewhere between 30 and 40 (in this case 34) conforms to the validation rule of the control. The RangeValidator control is not only about validating numbers (although it is most often used in this fashion). It can also be about validating a range of string characters as well as other items, including calendar dates. By default, the Type property of any of the validation controls is set to String .Youcan use the RangeValidator control to make sure what is entered in another server control (such as a calendar control) is within a certain range of dates. For example, suppose that you are building a Web form that asks for a customer’s arrival date, and the arrival date needs to be within two weeks of the current date. You can use the RangeValidator control to test for these scenarios quite easily. Because the date range that you want to check is dynamically generated, you assign the MaximumValue and MinimumValue attribute programmatically in the Page_Load event. In the Designer, your sample page for this example should look like Figure 4-4. Figure 4-4 207 Evjen c04.tex V2 - 01/28/2008 12:45pm Page 208 Chapter 4: Validation Server Controls The idea is that the end user will select a date from the Calendar control, which will then populate the TextBox control. Then, when the end user clicks the form’s button, he is notified if the date selected is invalid. If the date selected is valid, that date is presented through the Label control on the page. The code for this example is presented in Listing 4-12. Listing 4-12: Using the RangeValidator control to test a string date value VB < %@ Page Language="VB" % > < script runat="server" > Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) RangeValidator1.MinimumValue = DateTime.Now.ToShortDateString() RangeValidator1.MaximumValue = DateTime.Now.AddDays(14).ToShortDateString() End Sub Protected Sub Calendar1_SelectionChanged(ByVal sender As Object, _ ByVal e As System.EventArgs) TextBox1.Text = Calendar1.SelectedDate.ToShortDateString() End Sub Protected Sub Button1_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) If Page.IsValid Then Label1.Text = "You are set to arrive on: " & TextBox1.Text End If End Sub < /script > < html xmlns="http://www.w3.org/1999/xhtml" > < head runat="server" > < title > Date Validation Check < /title > < /head > < body > < form id="form1" runat="server" > Arrival Date: < asp:TextBox ID="TextBox1" runat="server" >< /asp:TextBox > &nbsp; < asp:RangeValidator ID="RangeValidator1" runat="server" Text="You must only select a date within the next two weeks." ControlToValidate="TextBox1" Type="Date" >< /asp:RangeValidator >< br / > < br / > Select your arrival date: < br / > < asp:Calendar ID="Calendar1" runat="server" OnSelectionChanged="Calendar1_SelectionChanged" >< /asp:Calendar > &nbsp; < br / > < asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" / > < br / > < br / > < asp:Label ID="Label1" runat="server" >< /asp:Label > 208 Evjen c04.tex V2 - 01/28/2008 12:45pm Page 209 Chapter 4: Validation Server Controls < /form > < /body > < /html > C# < %@ Page Language="C#" % > < script runat="server" > protected void Page_Load(object sender, EventArgs e) { RangeValidator1.MinimumValue = DateTime.Now.ToShortDateString(); RangeValidator1.MaximumValue = DateTime.Now.AddDays(14).ToShortDateString(); } protected void Calendar1_SelectionChanged(object sender, EventArgs e) { TextBox1.Text = Calendar1.SelectedDate.ToShortDateString(); } protected void Button1_Click(object sender, EventArgs e) { if (Page.IsValid) { Label1.Text = "You are set to arrive on: " + TextBox1.Text.ToString(); } } < /script > From this code, you can see that when the page is loaded, the MinimumValue and MaximumValue attributes are assigned a dynamic value. In this case, the MinimumValue gets the DateTime.Now.ToShortDate- String() value, while the MaximumValue gets a date of 14 days later. After the end user selects a date, the selected date is populated in the TextBox1 control using the Calendar1_SelectionChanged event. After a date is selected and the button on the page is clicked, the Button1_Click event is fired and the page is checked for form validity using the Page.IsValid property. An invalid page will give you the result shown in Figure 4-5. The RegularExpressionValidator Server Control One exciting control that developers like to use is the RegularExpressionValidator control. This control offers a lot of flexibility when you apply validation rules to your Web forms. Using the RegularExpres- sionValidator control, you can check a user’s input based on a pattern that you define using a regular expression. This means that you can define a structure that a user’s input will be applied against to see if its structure matches the one that you define. For instance, you can define that the structure of the user input must be in the form of an e-mail address or an Internet URL;ifitdoesn’tmatchthisdefinition,thepageis considered invalid. Listing 4-13 shows you how to validate what is input into a text box by making sure it is in the form of an e-mail address. 209 Evjen c04.tex V2 - 01/28/2008 12:45pm Page 210 Chapter 4: Validation Server Controls Figure 4-5 Listing 4-13: Making sure the text-box value is an e-mail address Email: < asp:TextBox ID="TextBox1" Runat="server" >< /asp:TextBox > &nbsp; < asp:RegularExpressionValidator ID="RegularExpressionValidator1" Runat="server" ControlToValidate="TextBox1" Text="You must enter an email address" ValidationExpression=" \ w+([-+.] \ w+)*@ \ w+([ ] \ w+)* \ . \ w+([ ] \ w+)*" > < /asp:RegularExpressionValidator > Just like the other validation server controls, the RegularExpressionValidator control uses the ControlTo- Validate property to bind itself to the TextBox control, and it includes a Text property to push out the error message to the screen if the validation test fails. The unique property of this validation control is the ValidationExpression property. This property takes a string value, which is the regular expression you are going to apply to the input value. Visual Studio 2008 makes it a little easier to use regular expressions through the use of the Regular Expression Editor. This editor provides a few commonly used regular expressions that you might want to apply to your RegularExpressionValidator. To get at this editor, you work with your page from Design view. Be sure to highlight the RegularExpressionValidator1 server control in this Design view to see the control’s properties. In the Property window of Visual Studio, click the button found next 210 Evjen c04.tex V2 - 01/28/2008 12:45pm Page 211 Chapter 4: Validation Server Controls to the ValidationExpression property to launch the Regular Expression Editor. This editor is shown in Figure 4-6. Figure 4-6 Using this editor, you can find regular expressions for things like e-mail addresses, Internet URLs, zip codes, phone numbers, and social security numbers. In addition to working with the Regular Expression Editor to help you with these sometimes complicated regular expression strings, you can also find a good-sized collection of them at an Internet site called RegExLib found at www.regexlib.com . The CustomValidator Server Control So far, you have seen a wide variety of validation controls that are at your disposal. In many cases, these validation controls address many of the validation rules that you want to apply to your Web forms. Sometimes, however, none of these controls works for you, and you have to go beyond what they offer. This is where the CustomValidator control comes into play. The CustomValidator control allows you to build your own client-side or server-side validations that can then be easily applied to your Web forms. Doing so allows you to make validation checks against values or calculations performed in the data tier (for example, in a database), or to make sure that the user’s input validates against some arithmetic validation (for example, determining if a number is even or odd). You can do quite a bit with the CustomValidator control. Using Client-Side Validation One of the worthwhile functions of the CustomValidator control is its capability to easily provide custom client-side validations. Many developers have their own collections of JavaScript functions they employ in their applications, and using the CustomValidator control is one easy way of getting these functions implemented. 211 Evjen c04.tex V2 - 01/28/2008 12:45pm Page 212 Chapter 4: Validation Server Controls For example, look at a simple form that asks for a number from the end user. This form uses the CustomValidator control to perform a custom client-side validation on the user input to make sure that the number provided is divisible by 5. This is illustrated in Listing 4-14. Listing 4-14: Using the CustomValidator control to perform client-side validations VB < %@ Page Language="VB" % > < script runat="server" > Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Label1.Text = "VALID NUMBER!" End Sub < /script > < html xmlns="http://www.w3.org/1999/xhtml" > < head runat="server" > < title > CustomValidator < /title > < script type="text/javascript" > function validateNumber(oSrc, args) { args.IsValid = (args.Value % 5 == 0); } < /script > < /head > < body > < form id="form1" runat="server" > < div > < p > Number: < asp:TextBox ID="TextBox1" Runat="server" >< /asp:TextBox > &nbsp; < asp:CustomValidator ID="CustomValidator1" Runat="server" ControlToValidate="TextBox1" Text="Number must be divisible by 5" ClientValidationFunction="validateNumber" > < /asp:CustomValidator > < /p > < p > < asp:Button ID="Button1" OnClick="Button1_Click" Runat="server" Text="Button" >< /asp:Button > < /p > < p > < asp:Label ID="Label1" Runat="server" >< /asp:Label > < /p > < /div > < /form > < /body > < /html > 212 Evjen c04.tex V2 - 01/28/2008 12:45pm Page 213 Chapter 4: Validation Server Controls C# < %@ Page Language="C#" % > < script runat="server" > protected void Button1_Click(Object sender, EventArgs e) { Label1.Text = "VALID NUMBER!"; } < /script > Looking over this Web form, you can see a couple of things happening. First, it is a simple form with only a single text box requiring user input. The user clicks the button that triggers the Button1_Click event, which in turn populates the Label1 control on the page. It carries out this simple operation only if all the validation checks are performed and the user input passes these tests. One item that is different about this page is the inclusion of the second < script > block found within the < head > section. This is the custom JavaScript. Note that Visual Studio 2008 is very friendly toward these kinds of constructions, even when you are switching between the Design and Code views of the page — something previous Visual Studio editions were rather poor at dealing with. This JavaScript function — validateNumber — is shown here: < script type="text/javascript" > function validateNumber(oSrc, args) { args.IsValid = (args.Value % 5 == 0); } < /script > This second < script > section is the client-side JavaScript that you want the CustomValidator control to use when making its validation checks on the information entered into the text box. The JavaScript functions you employ are going to use the args.IsValid property and set this property to either true or false depending on the outcome of the validation check. In this case, the user input ( args.Value )is checked to see if it is divisible by 5 . The Boolean value returned is then assigned to the args.IsValid property, which is then used by the CustomValidator control. The CustomValidator control, like the other controls before it, uses the ControlToValidate property to associate itself with a particular element on the page. The property that you are interested in here is the ClientValidationFunction property. The string value provided to this property is the name of the client-side function that you want this validation check to employ when the CustomValidator control is triggered. In this case, it is validateNumber : ClientValidationFunction="validateNumber" If you run this page and make an invalid entry, you produce the result illustrated in Figure 4-7. Using Server-Side Validation Now let’s move this same validation check from the client to the server. The CustomValidator control allows you to make custom server-side validations a reality as well. You will find that creating your server-side validations is just as easy as creating client-side validations. 213 . address or an Internet URL;ifitdoesn’tmatchthisdefinition,thepageis considered invalid. Listing 4- 13 shows you how to validate what is input into a text box by making sure it is in the form of. to enter in a number into the text box. If she attempts to bypass the validation by entering a fake value that contains anything other than a number, the page is identified as invalid, and the. illustrated in Listing 4-11. Listing 4-11: Using the RangeValidator control to test an integer value Age: < asp: TextBox ID="TextBox1" Runat="server" >< /asp: TextBox > &nbsp; < asp: RangeValidator

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

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

Tài liệu liên quan