Anda di halaman 1dari 6

3/2/2009 

Objectives 
Chapter 7  Applied
·  Given the data validation requirements for a web form, use any of 
the validation controls presented in this chapter to implement that 
How to use the  validation.
·  Create your own regular expression for use with a regular 
validation controls  expression validator. 
Knowledge
·  Describe the use of each of the six validation controls provided by 
ASP.NET.
·  Describe the use of the ErrorMessage and Text properties of a 
validation control.
·  Explain how ASP.NET processes validation controls. 

Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 1  Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 2 

Objectives (continued) Validation controls on an Order form 
·  Describe two types of validation that can be done by a required 
field validator.
·  Describe three types of validation that can be done by a compare 
validator.
·  Describe the use of validation groups.
·  Describe the use of the IsValid property of a page and the Validate 
method of a page.
·  List two common uses for the regular expression validator.
·  Describe the use of a custom validator. 

Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 3  Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 4 

The validation controls provided by ASP.NET  Common validator properties
·  ControlToValidate
Control  Name 
RequiredFieldValidator  ·  Display
CompareValidator  ·  ErrorMessage
RangeValidator  ·  Text
RegularExpressionValidator  ·  Enabled
CustomValidator  ·  EnableClientScript
ValidationSummary  ·  ValidationGroup
·  IsValid

Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 5  Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 6 


3/2/2009 

Typical code for processing a page that contains  Additional property of the required field validator 
validation controls 
Property  Description 
Protected Sub btnAdd_Click(ByVal sender As Object, _ 
ByVal e As System.EventArgs) Handles btnAdd.Click  InitialValue  The initial value of the control that’s validated. 
If Page.IsValid Then  If this value isn’t changed, the validation fails. 
Dim cartItem As New CartItem 
cartItem.Product = SelectedProduct  The default is an empty string. 
cartItem.Quantity = CInt(txtQuantity.Text) 
Me.AddToCart(cartItem) 
Response.Redirect("Cart.aspx") 
End If 
End Sub 

Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 7  Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 8 

A required field validator that checks for a  A required field validator that checks that an initial 
required entry  value is changed 
<asp:TextBox ID="txtBirthDate" runat="server" 
<asp:TextBox ID="txtName"  Width="159px">mm/dd/yyyy 
runat="server"></asp:TextBox>&nbsp;  </asp:TextBox>&nbsp; 
<asp:RequiredFieldValidator ID="RequiredFieldValidator1"  <asp:RequiredFieldValidator ID="RequiredFieldValidator2" 
runat="server"  runat="server" 
ControlToValidate="txtName"  ControlToValidate="txtBirthDate" 
ErrorMessage="You must enter a name.">  InitialValue="mm/dd/yyyy" 
</asp:RequiredFieldValidator>  ErrorMessage="You must enter a birth date."> 
</asp:RequiredFieldValidator> 

Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 9  Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 10 

A required field validator that forces an option to  How the input controls are initially displayed in a 
be chosen from a list box  browser
<asp:ListBox ID="lstCardType" runat="server" 
Width="292px"> 
<asp:ListItem Selected="True" Value="None"> 
­­Select a credit card­­</asp:ListItem> 
<asp:ListItem Value="Visa">Visa</asp:ListItem> 
<asp:ListItem Value="MC">MasterCard</asp:ListItem> 
<asp:ListItem Value="AmEx"> 
American Express</asp:ListItem> 
</asp:ListBox>&nbsp; 
<asp:RequiredFieldValidator ID="RequiredFieldValidator3" 
runat="server" 
ControlToValidate="lstCardType" 
InitialValue="None" 
ErrorMessage="You must select a credit card type."> 
</asp:RequiredFieldValidator> 

Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 11  Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 12 


3/2/2009 

Additional properties of the compare validator  A compare validator that checks for a value greater 
Property  Description  than zero 
ValueToCompare  The value that the control specified in the  <asp:TextBox ID="txtQuantity" runat="server"> 
</asp:TextBox>&nbsp; 
ControlToValidate property should be  <asp:CompareValidator ID="CompareValidator1" 
compared to.  runat="server" 
ControlToValidate="txtQuantity" Type="Integer" 
Operator  The type of comparison to perform (Equal,  Operator="GreaterThan" ValueToCompare="0" 
NotEqual, GreaterThan, GreaterThanEqual,  ErrorMessage="Quantity must be greater than zero."> 
LessThan, LessThanEqual, or  </asp:CompareValidator> 
DataTypeCheck). 
Type  The data type to use for the comparison 
(String, Integer, Double, Date, or Currency). 
ControlToCompare  The ID of the control that the value of the 
control specified in the ControlToValidate 
property should be compared to. 

Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 13  Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 14 

A compare validator that checks for an  A compare validator that compares the values 
integer value  of two text boxes 
<asp:TextBox ID="txtStartDate" runat="server"> 
<asp:TextBox id="txtQuantity" runat="server">  </asp:TextBox> 
</asp:TextBox>&nbsp;  <br /><br /> 
<asp:CompareValidator ID="CompareValidator2"  <asp:TextBox ID="txtEndDate" runat="server"> 
runat="server"  </asp:TextBox>&nbsp; 
ControlToValidate="txtQuantity" 
Operator="DataTypeCheck" Type="Integer"  <asp:CompareValidator 
ErrorMessage="Quantity must be an integer.">  ID="CompareValidator3" runat="server" 
</asp:CompareValidator>  ControlToValidate="txtEndDate" 
Operator="GreaterThan" Type="Date" 
ControlToCompare="txtStartDate" 
ErrorMessage= 
"End Date must be greater than Start Date."> 
</asp:CompareValidator> 

Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 15  Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 16 

Additional properties of the range validator  How to set a range at runtime 
Property  Description  A range validator that checks a date range set at runtime 
<asp:TextBox ID="txtArrival" 
MinimumValue  The minimum value allowed for the control.  runat="server">01/01/08</asp:TextBox>&nbsp; 
MaximumValue  The maximum value allowed for the control.  <asp:RangeValidator ID="valArrival" runat="server" 
ControlToValidate="txtArrival" Type="Date" 
Type  The data type to use for the comparison (String,  ErrorMessage="You must arrive within 30 days."> 
Integer, Double, Date, or Currency).  </asp:RangeValidator> 

A range validator that checks for a numeric range  Code that sets the minimum and maximum values 
<asp:TextBox ID="txtDays"  when the page is loaded 
runat="server"></asp:TextBox>&nbsp;  Protected Sub Page_Load(ByVal sender As Object, _ 
<asp:RangeValidator ID="RangeValidator1" runat="server"  ByVal e As System.EventArgs) Handles Me.Load 
ControlToValidate="txtDays" Type="Integer"  If Not IsPostBack Then 
MinimumValue="1" MaximumValue="14"  valArrival.MinimumValue = Today.ToShortDateString 
ErrorMessage="Days must be between 1 and 14.">  valArrival.MaximumValue = _ 
</asp:RangeValidator>  Today.AddDays(30).ToShortDateString 
End If 
End Sub

Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 17  Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 18 


3/2/2009 

Properties of the validation summary control 
Two validators and a validation summary control 
Property  Description 
that’s displayed on the web page 
DisplayMode  Specifies how the error messages from the 
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" 
validation controls are to be displayed.  The  runat="server" 
available values are BulletList, List, or  ControlToValidate="lstCardType" InitialValue="None" 
SingleParagraph. The default is BulletList.  ErrorMessage="You must select a credit card type." 
Display="Dynamic">*</asp:RequiredFieldValidator> 
HeaderText  The text that’s displayed before the list of 
error messages.  <asp:RequiredFieldValidator ID="RequiredFieldValidator2" 
runat="server" 
ShowSummary  A Boolean value that determines whether the  ControlToValidate="txtCardNumber" 
validation summary should be displayed on  ErrorMessage="You must enter a credit card number." 
the web page. The default is True.  Display="Dynamic">*</asp:RequiredFieldValidator> 

ShowMessageBox  A Boolean value that determines whether the  <asp:ValidationSummary ID="ValidationSummary1" 


validation summary should be displayed in a  runat="server" 
HeaderText="Please correct the following errors:"/> 
message box (client­side validation only). The 
default is False. 

Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 19  Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 20 

How the controls appear on the web page  Attributes that cause group validation when a 
button is clicked 
Attribute  Description 
CausesValidation  Specifies whether validation should be 
performed when the user clicks the button. 
ValidationGroup  Specifies the name of the group to be validated 
if CausesValidation is True. 

Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 21  Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 22 

A web page that accepts a bill­to and a ship­to  A text box with a validator that specifies a 
address  validation group 
<asp:TextBox ID="txtShipToName" runat="server" /> 
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" 
runat="server" 
ControlToValidate="txtShipToName" 
ErrorMessage="You must enter a ship­to name." 
ValidationGroup="ShipTo"></asp:RequiredFieldValidator> 

A button that specifies a validation group 
<asp:Button ID="btnContinue" runat="server" Text="Continue" 
ValidationGroup="BillTo" /> 

Visual Basic code that conditionally validates the 
ShipTo group 
If chkShipToSameAsBillTo.Checked = False Then 
Page.Validate("ShipTo") 
End If

Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 23  Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 24 


3/2/2009 

An additional property of the regular expression 
validator  A regular expression validator that validates 
Property  Description  U.S. phone numbers 
ValidationExpression  A string that specifies a regular  <asp:TextBox ID="txtPhone" runat="server"> 
</asp:TextBox>&nbsp; 
expression. The regular expression  <asp:RegularExpressionValidator 
defines a pattern that the input data  ID="RegularExpressionValidator2" 
must match to be valid.  runat="server" ControlToValidate="txtPhone" 
ValidationExpression= 
"((\(\d{3}\) ?)|(\d{3}­))?\d{3}­\d{4}" 
A regular expression validator that validates  ErrorMessage="Must be a valid U.S. phone number."> 
five­digit numbers  </asp:RegularExpressionValidator> 
<asp:TextBox ID="txtZipCode" 
runat="server"></asp:TextBox>&nbsp; 
<asp:RegularExpressionValidator 
ID="RegularExpressionValidator1" 
runat="server" ControlToValidate="txtZipCode" 
ValidationExpression="\d{5}" 
ErrorMessage="Must be a five­digit U.S. zip code."> 

Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 25  Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 26 

The Regular Expression Editor dialog box  Common regular expression elements 
Element  Description 
Ordinary character  Matches any character other than ., $, ^, [, {, (, |, ), 
*, +, ?, or \. 
\  Matches the character that follows. 
\d  Matches any decimal digit (0­9) 
\D  Matches any character other than a decimal digit. 
\w  Matches any word character (a­z, A­Z, and 0­9). 
\W  Matches any character other than a word character. 
\s  Matches any white space character (space, tab, 
new line, etc.). 
\S  Matches any character other than a whitespace 
character. 

Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 27  Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 28 

Common regular expression elements (continued) 
Common regular expression elements (continued) 
Element  Description 
Element  Description 
[abcd]  Matches any character included between the 
?  Matches zero or one occurrence of the preceding 
brackets. 
element. 
[^abcd]  Matches any character that is not included between 
+  Matches one or more occurrences of the preceding 
the brackets. 
element. 
[a­z]  Matches any characters in the indicated range. 
|  Matches any of the elements separated by the vertical 
{n}  Matches exactly n occurrences of the preceding  bar. 
element or group. 
(  )  Groups the elements that appear between the 
{n,}  Matches at least n occurrences of the preceding  parentheses.
element or group. 
{n,m}  Matches at least n but no more than m occurrences 
of the preceding element or group. 
*  Matches zero or more occurrences of the preceding 
element. 

Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 29  Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 30 


3/2/2009 

Properties of the ServerValidateEventArgs class 
Examples of regular expressions 
Property  Description 
Expression  Example 
Value  The text string to be validated. 
\d{3}  289 
IsValid  A Boolean property that you set to True if the 
\w{8,20}  Frankenstein  value passes the validation test or to False 
\d{2}­\d{4}  10­3944  otherwise. 
\w{1,8}.\w{1,3}  freddy.jpg 
Aspx code for a text box and a custom validator 
(AB)|(SB)­\d{1,5}  SB­3276  <asp:TextBox ID="txtProductCode" 
\d{5}(­\d{4})?  93711­2765  runat="server"></asp:TextBox>&nbsp; 
<asp:CustomValidator id="valProductCode" runat="server" 
\w*\d\w*  arm01  ControlToValidate="txtProductCode" 
[xyz]\d{3}  x023  ErrorMessage="Product code must be in database."> 

Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 31  Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 32 

VB code for a credit card validator 
Visual Basic code for the custom validator  Protected Sub valCreditCardNumber_ServerValidate( _ 
Protected Sub valProductCode_ServerValidate( _  ByVal source As Object, _ 
ByVal source As Object, _  ByVal args As _ 
ByVal args As _  System.Web.UI.WebControls.ServerValidateEventArgs) _ 
System.Web.UI.WebControls.ServerValidateEventArgs) _  Handles valCreditCardNumber.ServerValidate 
Handles valProductCode.ServerValidate  args.IsValid = ValidateCreditCard(args.Value) 
args.IsValid = HalloweenDB.CheckProductCode(args.Value)  End Sub 
End Sub 
Private Function ValidateCreditCard( _ 
ByVal cardNumber As String) As Boolean 
Dim digitSum As Integer 
Dim digits As String = "" 
Dim i As Integer 
'Remove spaces and reverse string 
cardNumber = _ 
StrReverse(cardNumber.Replace(" ", Nothing)) 

Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 33  Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 34 

VB code for a credit card validator (continued)  What the mod 10 validation algorithm does
'Double the digits in even­numbered positions 
For i = 0 To cardNumber.Length ­ 1  ·  Removes any spaces from the number.
If (i + 1) Mod 2 = 0 Then  ·  Reverses the number.
digits &= _ 
CInt(cardNumber.Substring(i, 1)) * 2  ·  Doubles the digits in even­numbered positions. If the original digit 
Else  is 5 or greater, this will insert an additional digit into the number.
digits &= cardNumber.Substring(i, 1) 
End If  ·  Adds up the individual digits.
Next 
'Add the digits  ·  Divides the result by 10. If the remainder is 0, the credit card 
For i = 0 To digits.Length ­ 1  number is valid.
digitSum += CInt(digits.Substring(i, 1)) 
Next 
'Check that the sum is divisible by 10 
If digitSum Mod 10 = 0 Then 
Return True 
Else 
Return False 
End If 
End Function 

Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 35  Murach’s ASP.NET  3.5/VB,  C7  © 2008,  Mike  Murach & Associates, Inc.  Slide 36 

Anda mungkin juga menyukai