Objectives: • 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. • 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.

Chapter 7

How to use the validation controls Spring 2007 Prof. Rasley

Murach’s ASP.NET 2.0/VB, C7

© 2006, Mike Murach & Associates, Inc.

Slide 1

© 2006, Mike Murach & Associates, Inc.

Slide 2

Common validator properties

The validation controls provided by ASP.NET Control

Murach’s ASP.NET 2.0/VB, C7

• ControlToValidate

Name RequiredFieldValidator CompareValidator RangeValidator RegularExpressionValidator CustomValidator

• Display • ErrorMessage • Text • Enabled • EnableClientScript • ValidationGroup

ValidationSummary

• IsValid

Murach’s ASP.NET 2.0/VB, C7

© 2006, Mike Murach & Associates, Inc.

Slide 3

Murach’s ASP.NET 2.0/VB, C7

© 2006, Mike Murach & Associates, Inc.

Slide 4

1

Where is validation performed? Typical code for processing a page that contains validation controls

• On the client if JavaScript is enabled • Also on the server… • This is a security measure so that a fake form is not posted back to the server with invalid data on it • Client-side validation may be disabled by setting the EnableClientScript property to false

Murach’s ASP.NET 2.0/VB, C7

© 2006, Mike Murach & Associates, Inc.

Protected Sub btnAdd_Click(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles btnAdd.Click If Page.IsValid Then Dim CartItem As New CartItem CartItem.Product = SelectedProduct CartItem.Quantity = CType(txtQuantity.Text, Integer) Me.AddToCart(CartItem) Response.Redirect("Cart.aspx") End If End Sub

Slide 5

Additional property of the required field validator Property InitialValue

Murach’s ASP.NET 2.0/VB, C7

Description The initial value of the control that’s validated. If this value isn’t changed, the validation fails. The default is an empty string.

© 2006, Mike Murach & Associates, Inc.

Murach’s ASP.NET 2.0/VB, C7

© 2006, Mike Murach & Associates, Inc.

Slide 6

A required field validator that forces an option to be chosen from a list box --Select a credit card-- Visa MasterCard American Express  

Slide 7

Murach’s ASP.NET 2.0/VB, C7

© 2006, Mike Murach & Associates, Inc.

Slide 8

2

Additional properties of the compare validator

How the input controls are initially displayed in a browser

Murach’s ASP.NET 2.0/VB, C7

© 2006, Mike Murach & Associates, Inc.

Property ValueToCompare

Description The value that the control specified in the ControlToValidate property should be compared to. Operator The type of comparison to perform (Equal, NotEqual, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual, or 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.

Slide 9

Murach’s ASP.NET 2.0/VB, C7

© 2006, Mike Murach & Associates, Inc.

Slide 10

A compare validator that checks for a value greater than zero  

A compare validator that compares the values of two text boxes



A compare validator that checks for a numeric entry  

Murach’s ASP.NET 2.0/VB, C7

© 2006, Mike Murach & Associates, Inc.

Slide 11

Murach’s ASP.NET 2.0/VB, C7

© 2006, Mike Murach & Associates, Inc.

Slide 12

3

How to set a range at runtime

Additional properties of the range validator Property MinimumValue MaximumValue Type

Description The minimum value allowed for the control. The maximum value allowed for the control. The data type to use for the comparison (String, Integer, Double, Date, or Currency).

A range validator that checks for a numeric range  

Murach’s ASP.NET 2.0/VB, C7

© 2006, Mike Murach & Associates, Inc.

Slide 13

Properties of the validation summary control Property DisplayMode

HeaderText ShowSummary

ShowMessageBox

Murach’s ASP.NET 2.0/VB, C7

Murach’s ASP.NET 2.0/VB, C7

© 2006, Mike Murach & Associates, Inc.

Slide 14

Two validators and a validation summary control that’s displayed on the web page

Description Specifies how the error messages from the validation controls are to be displayed. The available values are BulletList, List, or SingleParagraph. The default is BulletList. The text that’s displayed before the list of error messages. A Boolean value that determines whether the validation summary should be displayed on the web page. The default is True. A Boolean value that determines whether the validation summary should be displayed in a message box (client-side validation only). The default is False.

© 2006, Mike Murach & Associates, Inc.

A range validator that checks a date range set at runtime 01/01/06  Code that sets the minimum and maximum values when the page is loaded Protected Sub Page_Load(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Load If Not IsPostBack Then valArrival.MinimumValue = Today.ToShortDateString valArrival.MaximumValue = _ Today.AddDays(30).ToShortDateString End If End Sub

* *

Slide 15

Murach’s ASP.NET 2.0/VB, C7

© 2006, Mike Murach & Associates, Inc.

Slide 16

4

How the controls appear on the web page

Attributes that cause group validation when a button is clicked Attribute CausesValidation ValidationGroup

Murach’s ASP.NET 2.0/VB, C7

© 2006, Mike Murach & Associates, Inc.

Slide 17

© 2006, Mike Murach & Associates, Inc.

Slide 18

A regular expression validator that validates U.S. phone numbers

An additional property of the regular expression validator Property ValidationExpression

Murach’s ASP.NET 2.0/VB, C7

Description Specifies whether validation should be performed when the user clicks the button. Specifies the name of the group to be validated if CausesValidation is True.

Description A string that specifies a regular expression. The regular expression defines a pattern that the input data must match to be valid.

A regular expression validator that validates fivedigit numbers



The Regular Expression Editor dialog box



Murach’s ASP.NET 2.0/VB, C7

© 2006, Mike Murach & Associates, Inc.

Slide 19

Murach’s ASP.NET 2.0/VB, C7

© 2006, Mike Murach & Associates, Inc.

Slide 20

5

Common regular expression elements

Common regular expression elements (continued)

Element Ordinary character

Element [abcd]

\ \d \D \w \W \s \S

Description Matches any character other than ., $, ^, [, {, (, |, ), *, +, ?, or \. Matches the character that follows. Matches any decimal digit (0-9) Matches any character other than a decimal digit. Matches any word character (a-z, A-Z, and 0-9). Matches any character other than a word character. Matches any white space character (space, tab, new line, etc.). Matches any character other than a whitespace character.

[^abcd] [a-z] {n} {n,} {n,m} *

Murach’s ASP.NET 2.0/VB, C7

© 2006, Mike Murach & Associates, Inc.

Slide 21

Murach’s ASP.NET 2.0/VB, C7

Description Matches any character included between the brackets. Matches any character that is not included between the brackets. Matches any characters in the indicated range. Matches exactly n occurrences of the preceding element or group. Matches at least n occurrences of the preceding element or group. 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.

© 2006, Mike Murach & Associates, Inc.

Common regular expression elements (continued)

Examples of regular expressions

Element ?

Expression \d{3} \w{8,20} \d{2}-\d{4} \w{1,8}.\w{1,3} (AB)|(SB)-\d{1,5} \d{5}(-\d{4})? \w*\d\w* [xyz]\d{3}

+ | ( )

Murach’s ASP.NET 2.0/VB, C7

Description Matches zero or one occurrence of the preceding element. Matches one or more occurrences of the preceding element. Matches any of the elements separated by the vertical bar. Groups the elements that appear between the parentheses.

© 2006, Mike Murach & Associates, Inc.

Slide 23

Murach’s ASP.NET 2.0/VB, C7

Slide 22

Example 289 Frankenstein 10-3944 freddy.jpg SB-3276 93711-2765 arm01 x023

© 2006, Mike Murach & Associates, Inc.

Slide 24

6

Properties of the ServerValidateEventArgs class Property Value IsValid

Description The text string to be validated. A Boolean property that you set to True if the value passes the validation test or to False otherwise.

VB code for a credit card validator Private Sub valCreditCardNumber_ServerValidate( _ ByVal source As Object, _ ByVal args As _ System.Web.UI.WebControls.ServerValidateEventArgs) _ Handles valCreditCardNumber.ServerValidate args.IsValid = ValidateCreditCard(args.Value) End Sub

Aspx code for a text box and a custom validator

Visual Basic code for the custom validator Private Sub valProductCode_ServerValidate( _ ByVal source As Object, _ ByVal args As _ System.Web.UI.WebControls.ServerValidateEventArgs) _ Handles valProductCode.ServerValidate args.IsValid = HalloweenDB.CheckProductCode(args.Value) End Sub Murach’s ASP.NET 2.0/VB, C7

© 2006, Mike Murach & Associates, Inc.

Slide 25

VB code for a credit card validator (continued) For i = 0 To CardNumber.Length - 1 If (i + 1) Mod 2 = 0 Then sDigits &= _ CType(CardNumber.Substring(i, 1), Integer) * 2 Else sDigits &= CardNumber.Substring(i, 1) End If Next 'Add the digits For i = 0 To sDigits.Length - 1 iDigitSum += CType(sDigits.Substring(i, 1), Integer) Next 'Check that the sum is divisible by 10 If iDigitSum Mod 10 = 0 Then Return True Else Return False End If End Function

Murach’s ASP.NET 2.0/VB, C7

© 2006, Mike Murach & Associates, Inc.

Slide 27

Private Function ValidateCreditCard( _ ByVal CardNumber As String) As Boolean Dim iDigitSum As Integer Dim sDigits As String = "" Dim i As Integer 'Remove spaces and reverse string CardNumber = _ StrReverse(CardNumber.Replace(" ", Nothing)) 'Double the digits in even-numbered positions

Murach’s ASP.NET 2.0/VB, C7

© 2006, Mike Murach & Associates, Inc.

Slide 26

What the mod 10 validation algorithm does • Removes any spaces from the number. • Reverses the number. • Doubles the digits in even-numbered positions. If the original digit is 5 or greater, this will insert an additional digit into the number. • Adds up the individual digits. • Divides the result by 10. If the remainder is 0, the credit card number is valid.

Murach’s ASP.NET 2.0/VB, C7

© 2006, Mike Murach & Associates, Inc.

Slide 28

7