Teach Yourself Visual Studio® .NET 2003 in 21 Days [Electronic resources] نسخه متنی

اینجــــا یک کتابخانه دیجیتالی است

با بیش از 100000 منبع الکترونیکی رایگان به زبان فارسی ، عربی و انگلیسی

Teach Yourself Visual Studio® .NET 2003 in 21 Days [Electronic resources] - نسخه متنی

Jason Beres

| نمايش فراداده ، افزودن یک نقد و بررسی
افزودن به کتابخانه شخصی
ارسال به دوستان
جستجو در متن کتاب
بیشتر
تنظیمات قلم

فونت

اندازه قلم

+ - پیش فرض

حالت نمایش

روز نیمروز شب
جستجو در لغت نامه
بیشتر
لیست موضوعات
توضیحات
افزودن یادداشت جدید











Using Validation Controls



Visual Studio .NET comes with built-in validation controls for use in ASPX pages. When you validate a control, you''re checking whether a control has data in it and conforms to a specific pattern, (such as an email address), or you''re checking the range of data that has been entered.


In ASP, you either had to process the validation on the server and send the page back to the browser if data wasn''t correctly entered, or you had to write complex JavaScript to check the validity of control data. ASP.NET has five built-in validation controls in the Toolbox that you can simply drag to a form and associate with a control. Table 5.2 lists the validation controls and gives a description of how you can use each one.
































Table 5.2. Validation Controls in ASP.NET


Control Name




Description




RequiredFieldValidator




Forces the user to enter a value into the specified control.




CompareValidator




Compares a user''s entry against a constant value, or against a property value of another control, using a comparison operator.




RangeValidator




Checks that a user''s entry is between specified lower and upper boundaries. You can check ranges within pairs of numbers, alphabetic characters, and dates.




RegularExpressionValidator




Checks that the entry matches a pattern defined by a regular expression.




CustomValidator




Checks the user''s entry using validation logic that you write yourself. This type of validation allows you to check for values derived at runtime.



Each validation control has properties specific to the functionality the control provides. For example, the RequiredFieldValidator has a ControlToValidate property and an ErrorMessage property. The ControlToValidate property takes the ID of a valid control on the form. The RegularExpressionValidator uses the regular expression syntax of .NET to validate the data entered in a control against a regular expression pattern.



Note


Each validation control has a Text property and an ErrorMessage property. The Text property is like the Text property of a Label controlit simply displays text. This could be used to display Required or an * for a RequiredFieldValidator control. The ErrorMessage property displays if an error occurs in the validation.


To test the validation controls, let''s add a new Web Form to your solution. Right-click the project name in the Solution Explorer and select Add, Add Web Form from the contextual menu. When the Add New Item dialog pops up, change the name from WebForm2.aspx to Success.aspx, as Figure 5.12 demonstrates.


Figure 5.12. Add New Item dialog box.





You should now see a new ASPX page called Success.aspx is added to your solution, and the Success.aspx page should be in the Web Forms Designer. Double-click Success.aspx to get to the Form_Load event for the page, and add the code in Listing 5.5 to the Page_Load event.


Listing 5.5 Code-Behind for the Page_Load Event of the Success.aspx Page



Private Sub Page_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
Response.Write("<H1>You are now logged in</H1>")
End Sub



private void Page_Load(object sender, System.EventArgs e)
{
Response.Write("<H1>You are now logged in</H1>");
}


In Listing 5.5, you use the Response object''s Write method to render You are now logged in. This page is called from the WebForm1.aspx page if the correct username and password are entered.


To modify the WebForm1.aspx page, you must do the following:





  1. Add a new table row above the Log In button. You can add a new row to the table by clicking inside the cell that contains the Log In button, and then right-clicking and selecting Insert, Row Above from the contextual menu. Most of the options you need for manipulating tables and controls can be accessed by right-clicking on the objects in the designer.



  2. In the newly added row, drag a Label and TextBox from the Web Forms tab of the Toolbox to line up with the other controls in the table. Change the Text property of the Label control to Re-Enter Password, and change the ID property of the TextBox control to Password2.



  3. Change the Text property of the Label control that says UserName: to now say Email Address:.



  4. Drag a RequiredFieldValidator control to the form from the Web Form tab of the Toolbox, and place it in the column next to the Username TextBox.



  5. From the Web Form tab of the Toolbox, drag a RegularExpressionValidator control and place it next to the RequiredFieldValidator control you just added.



  6. From the Web Form tab of the Toolbox, drag a RequiredFieldValidator control to the form and place it in the column next to the Password TextBox.



  7. From the Web Form tab of the Toolbox, drag a CompareValidator control to the form and place it in the column next to the Password2 TextBox.




Your WebForm1.aspx should now look like Figure 5.13.


Figure 5.13. WebForm1.aspx after adding new controls and validation controls.





The next step is to set the properties on the validation controls. Follow these steps to do so:





  1. Select the RequiredFieldValidator1 control, and change the ControlToValidate property to UserName. Then change the ErrorMessage property to "Email Address Required".



  2. Select the RegularExpressionValidator. In the ValidationExpression property, click the ellipses (…) button to get to the Regular Expression Editor dialog box. Scroll down the list until you see the Internet Email Address regular expression. Select it and click the OK button. Change the ErrorMessage property to "Invalid Email Format", and change the ControlToValidate property to Username.



  3. Select the RequiredFieldValidator2 control, and change the ControlToValidate property to Password. Then change the ErrorMessage property to "Password Required".



  4. Select the CompareValidator1 control, and change the ControlToCompare property to Password. Change the ControlToValidate property to Password2, and change the ErrorMessage property to "Passwords do not match".




When I mentioned regular expressions earlier, you might''ve gotten a little scared. But you can see that, once again, the Visual Studio .NET team thought of everything. Using the Regular Expression Editor, you can not only easily select a predefined regular expression for common data formats, but you also get a head start on understanding the regular expression syntax.


The next step is to rename the WebForm1.aspx to Login.aspx. To do so, right-click WebForm1.aspx in the Solution Explorer, and select Rename from the contextual menu. You can now change the name to Login.aspx. Make sure that you include the .aspx extension, or you''ll get an error.


Now that you''ve set these properties and renamed your form, your Login.aspx should look like Figure 5.14.


Figure 5.14. Notice also that when you renamed your form, the WebForm1.aspx.vb or WebForm1.aspx.cs code-behind class file was also renamed.





Now, double-click the Log In button, and add the code in Listing 5.6.


Listing 5.6 Code-Behind for the LogIn_Click Event in the Login.aspx Page



Private Sub LogIn_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles LogIn.Click
If UserName.Text = "jason@fladotnet.net" _
And Password.Text = "password" Then
Response.Redirect("Success.aspx")
Else
LogIn.Text = "Invalid Data, please retry"
End If
End Sub



private void LogIn_Click(object sender, System.EventArgs e)
{
if (UserName.Text == "jason@fladotnet.net"
&& Password.Text == "password")
{
Response.Redirect(@"Success.aspx");
}
}


Tip


To make your user interface more friendly, you can set the InitialValue property of the RequiredFieldValidator control to a red asterisk or some other visual clue to the end user that the fields are required. You should also set the TextMode property of the Password and Password2 text boxes to Password so that the data entered into the field is filled with asterisks, and isn''t visible to prying eyes.


Now you can build the solution, right-click the Login.aspx page, and select Browse from the contextual menu. After the page is in the browser, test the validation controls. Enter text that isn''t an email address, and type different passwords in the Password text box and Password2 text box. When you do so, your form will look something like Figure 5.15.


Figure 5.15. Testing the Login.aspx validation controls.




Day 7, "Exceptions, Debugging, and Tracing."


Notice that when you click on the Log In button, the page is never posted to the server. When you place a validation control on a form, ASP.NET automatically adds custom client-side JavaScript when the page is rendered, so the validation occurs on the client and the page isn''t posted to the server until the data is correct. Listing 5.7 is the HTML that''s rendered to the browsernotice the JavaScript that''s been added.


Listing 5.7 HTML Source with Client-Side JavaScript for Validation Rendered


[View full width]



<form name="Form1" method="post" action="Login.aspx"
language="javascript" onsubmit="ValidatorOnSubmit();" id="Form1">
<script language="javascript"
src="/image/library/english/10210_WebUIValidation.js"></script>
<P>
<TABLE id="Table1" width="469" border="1">
<TR>
<TD><span id="Label1">Email Address:</span></TD>
<TD><input name="UserName" type="text" id="UserName" /></TD>
<TD><span id="RequiredFieldValidator1" controltovalidate="UserName"
errormessage="Email Required"
evaluationfunction="RequiredFieldValidatorEvaluateIsValid"
initialvalue="
style="color:Red;visibility:hidden;">Email Required</span>
<span id="RegularExpressionValidator1"
controltovalidate="UserName"
errormessage="Invalid Email Format"
evaluationfunction="RegularExpressionValidatorEvaluateIsValid"
validationexpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"
style="color:Red;visibility:hidden;">Invalid Email Format</span>
</TD>
</TR>
<TR>
<TD><span id="Label2">Password:</span></TD>
<TD><input name="Password" type="text" id="Password" /></TD>
<TD><span id="RequiredFieldValidator2"
controltovalidate="Password"
errormessage="Password Required"
evaluationfunction="RequiredFieldValidatorEvaluateIsValid"
initialvalue="
style="color:Red;visibility:hidden;">Password Required</span>
</TD>
</TR>
<TR>
<TD>Re-Enter Password</TD>
<TD><input name="Password2" type="text" id="Password2" /></TD>
<TD><span id="CompareValidator1"
controltovalidate="Password2"
errormessage="Passwords do not match!"
evaluationfunction="CompareValidatorEvaluateIsValid"
controltocompare="Password"
controlhookup="Password"
style="color:Red;visibility:hidden;">
Passwords do not match!</span>
</TD>
</TR>
<TR>
<TD></TD>
<TD><input type="submit" name="LogIn" value="Log In"
onclick="if (typeof(Page_ClientValidate) == ''function'')
Page_ClientValidate(); "
language="javascript" id="LogIn" />
</TD>
<TD></TD>
</TR>
</TABLE>
</P>
</P>
<script language="javascript">
<!--
var Page_Validators =
new Array(document.all["RequiredFieldValidator1"],
document.all["RegularExpressionValidator1"],
document.all["RequiredFieldValidator2"],
document.all["CompareValidator1"]);
// -->
</script>
<script language="javascript">
<!--
var Page_ValidationActive = false;
if (typeof(clientInformation) != "undefined" &&
clientInformation.appName.indexOf("Explorer") != -1) {
if (typeof(Page_ValidationVer) == "undefined")
alert("Unable to find script library
''/image/library/english/10210_WebUIValidation.js''.
Try placing this file manually, or reinstall by running
''aspnet_regiis -c''.");
else if (Page_ValidationVer != "125")
alert("This page uses an incorrect version of WebUIValidation.js.
The page expects version 125. The script library is "
+ Page_ValidationVer + ".");
else
ValidatorOnLoad();
}
function ValidatorOnSubmit() {
if (Page_ValidationActive) {
ValidatorCommonOnSubmit();
}
}
// -->
</script>
</form>


You can see that the HTML output is now vastly different from the output before adding validation controls, and the inserted client-side script was done by ASP.NET.


In the root wwwroot directory of your server, there''s a folder named asp_client, which is used in conjunction with this script to make sure that the validation occurs. If you ever add validation to your pages and you get an error about validation files not being found when the page loads in the browser, make sure that the asp_client folder exists in the root of your wwwroot directory or in the actual folder of your Web site in the IIS server.


To see what happens with validation controls in Netscape version 4.79, check out Figure 5.16.


Figure 5.16. Running the validation controls in Netscape 4.79.





When ASP.NET detects that a down-level browser, such as Netscape 4.79, is attempting to access a page that uses validation controls, it simply changes the validation events to occur on the server. You don''t need to do anything special to make this happenit''s automatic.


To display a summary of validation errors, you can use the ValidationSummary control on a page. This takes all the validation errors on the page, and places them in a nice bulleted list. Figure 5.17 demonstrates the use of a ValidationSummary control with the ShowMessageBox property set to True.


Figure 5.17. Using a ValidationSummary control.





To validate a page in server-side code, you check the IsValid property of a page. When you check the IsValid property for an entire page, all the validation controls on the page are checked against their respective controls to validate. If they''re all okay, processing continues. If there are errors, processing stops and the validation controls or ValidationSummary control will be filled.


You can use this method of server-side validation checking by setting the EnableClientScript property to False for each validation control. In Listing 5.8 the Visual Basic .NET code (used in the Page_Load event) checks the IsValid property to check controls on the page against their validation controls.


Listing 5.8 Using the IsValid Method of the Page Class to Validate a Page



If Page.IsValid Then
If UserName.Text = "jason@fladotnet.net" _
And Password.Text = "password" Then
Response.Redirect("Success.aspx")
Else
LogIn.Text = "Invalid Data, please retry"
End If
End If


No matter what kind of validation you use, Visual Studio .NET makes it so easy to actually implement validation that you should always include it. Here''s a user interface tip: Try to validate controls on the client side. There''s nothing worse than going to a Web site, filling out a bunch of fields, clicking a Submit button, and then waiting for someone''s slow Internet server to refresh the page just to tell you that you forgot to complete the Zipcode field or State field correctly.



/ 270