Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

C# ПІДРУЧНИКИ / c# / Hungry Minds - ASP.NET Bible VB.NET & C#

.pdf
Скачиваний:
128
Добавлен:
12.02.2016
Размер:
7.64 Mб
Скачать

id="rvTickets"

controltovalidate="Tickets"

minimumvalue=1

maximumvalue=4

type="Integer"

display="dynamic"

errormessage="You can only purchase 1 to 4 tickets, please try again."

runat="Server">

</asp:rangevalidator><br>

Launch your browser and navigate to Range.aspx. A screen similar to Figure 6-8 is displayed.

Figure 6-8: Range validator control example 1

As you can see from the code fragment, the MinimumValue property is set to 1 and the MaximumValue property is set to 4. Now, enter a value less than 1 or greater than 8 in the Number of tickets field and then press the Tab key. A screen similar to Figure 6-9 should be displayed.

Figure 6-9: Range validator control example 2

Because you specified a range of 1 to 8, any other value will fail validation and your error message will be displayed. Enter a value within the range and then click Validate. A screen similar to Figure 6-10 is displayed.

Figure 6-10: Range validator control example 3

MinimumControl and MaximumControl properties

As mentioned in the previous section, the RangeValidator control is useful when you need to make sure that a value falls within a specified range of values. You can specify values for the MinimumControl and MaximumControl properties for the range just as easily as you did for the MinimumValue and MaximumValue properties previously. Try it! Add two controls to the form and then set the MaximumControl and MinimumControl properties to these new controls. Make sure that you remove the

MinimumValue and MaximumValue properties.

Using the RegularExpressionValidator Control

Use the RegularExpressionValidator control to check a value against a regular expression. It checks whether the value of the associated input control matches the

pattern of a regular expression. Table 6-4 lists the properties commonly used with the RegularExpressionValidator control.

Table 6-4: Properties of the RegularExpressionValidator control

Property

ID

Definition

This property gets or sets the identifier for the control. This identifier is used via programm ing to access the control's properties. If an identifier does not exist, then you cannot write handlers for this control.

ControlToValidate

 

Gets or

 

 

 

 

sets the

 

 

name of

 

 

the control

 

 

to

 

 

validate.

 

 

 

ValidationExpression

 

Gets or

 

 

 

 

sets the

 

 

regular

 

 

expressio

 

 

n that is

 

 

used as

 

 

the

 

 

validation

 

 

criteria.

 

 

 

Display

 

Gets or

 

 

 

 

sets the

 

 

display

 

 

appearanc

 

 

e of the

 

 

validator

 

 

control on

 

 

the Web

 

 

page.

 

 

 

ErrorMessage

 

Gets or

 

 

 

 

sets the

Table 6-4: Properties of the RegularExpressionValidator control

Property

RunAt

Definition

error message displayed for this control.

Specifies that this control runs on the server.

This control allows you to check for known sequences in characters, such as phone numbers, social security numbers, and so on. Take a look at the following code fragment for the Regular ExpressionValidator control:

<!-- Regular Expression Validator Control -->

Phone:<br>

<asp:textbox id="Phone" maxlength="12" columns="12" runat="Server"/>

<asp:regularexpressionvalidator

id="revPhone"

controltovalidate="Phone"

display="dynamic"

validationexpression="[0-9]{3}\s[0-9]{3}-[ 0-9]{4}"

errormessage="Phone number format must be xxx xxx-xxxx, please try again."

runat="Server">

</asp:regularexpressionvalidator><br>

Note that the string assigned to the ValidationExpression property uses JScript regular expression syntax. Regular expressions are beyond the scope of this book, but the following explanation will help. The ValidationExpression property in the preceding code fragment means the following:

§First sequence

[0-9]: Any digit from 0 to 9

{3}: Three digits are required for this first group of numbers \s: A space is required

§Second sequence [0-9]: Any digit from 0 to 9

{3}: Three digits are required for this first group of numbers -: A dash is required

§Third sequence

[0-9]: Any digit from 0 to 9

{4}: Four digits are required for this first group of numbers

For more help on JScript regular expression, visit the Microsoft MSDN Note Web site on scripting at http://msdn.microsoft.com/library/en-us/script56/

html/js56reconIntroductionToRegularExpressions.asp.

Run the sample for this control by launching your browser and navigating to Regular.aspx, shown in Figure 6-11.

Figure 6-11: Regular expression validator control example 1

Because the format in your ValidationExpression is xxx xxx-xxxx, enter some other phone sequence to test the validation control. After you enter the value, press the Tab key, and Figure 6-12 displays.

Figure 6-12: Regular expression validator control example 2

Because the phone number is not in the expected format, validation fails and your error message is displayed. This time, enter the correct phone number format and then click the Validate button. The validation message is cleared from the page and your message is displayed. Your screen should look like Figure 6-13.

Figure 6-13: Regular expression validator control example 3

With the RegularExpressionValidator control, you can verify known sequences of characters without building your own validation routines from scratch. However, you can create custom validation routines, as well, which is the purpose of the next validation control in ASP.NET, CustomValidator.

Using the CustomValidator Control

Use the CustomValidator control to perform user-defined custom validation. This control allows custom code to perform validation on the client and/or server. Table 6-5 lists the properties commonly used with the CustomValidator control.

Table 6-5: Properties of the CustomValidator control

Property

ID

Definition

This property gets or sets the identifier for the control. This identifier is used via programm ing to access the control's properties. If an identifier does not exist, then you cannot write handlers for this control.

When using server-side events, remember to always prefix the event name with the word on. For instance, onServerValidate, which is the required syntax for this event.

Table 6-5: Properties of the CustomValidator control

Property

ControlToValidate

Definition

Gets or sets the name of the control to validate.

ClientValidationFunction

 

Indicates

 

 

 

 

the client

 

 

script

 

 

function to

 

 

call for

 

 

validation.

 

 

 

OnServerValidate

 

Indicates

 

 

 

 

the name

 

 

of the

 

 

event to

 

 

raise on

 

 

the server.

 

 

 

Display

 

Gets or

 

 

 

 

sets the

 

 

display

 

 

appearanc

 

 

e of the

 

 

validator

 

 

control on

 

 

the Web

 

 

page.

 

 

 

ErrorMessage

 

Gets or

 

 

 

 

sets the

 

 

error

 

 

message

 

 

displayed

 

 

for this

 

 

control.

 

 

 

RunAt

 

Specifies

 

 

 

 

that this

 

 

control

 

 

runs on

 

 

the server.

Because the client validation function runs on the target browser, the function needs to be written using a scripting language supported by the browser, such as JavaScript or VBScript. The CustomValidator control also has an event that can be set for server-side validation.

Note

Take a look at the code fragment for the CustomValidator control:

<!-- Custom Validator Control -->

Credit card number:<br>

<asp:textbox id="CardNumber" maxlength="16" columns="16" runat="Server"/>

<asp:customvalidator

id="cvCardNumber"

controltovalidate="CardNumber"

ClientValidationFunction="IsCardValid"

display="dynamic"

errormessage="Invalid credit card number, please try again."

runat="Server">

</asp:customvalidator><br>

By now, you should be familiar with most of the properties when wiring up the validation controls. However, for the CustomValidator control, you are interested in the

ClientValidationFunction or the OnServerValidate event. In the example, you are going to concentrate on the ClientValidationFunction event. Here, this property points to the IsCardValid function, which must be a valid function defined as JScript or VBScript on the client. Take a look at the code for this function:

<script language="javascript">

//--- source is the name of control that is being checked

//--- value is actual value that is entered into the control

function IsCardValid(source, value) {

if (value != "5555555555555555" )

return false;

else

return true;

}

</script>

The ClientValidationFunction event expects two parameters:

§source: The name of the control that is being validated, pointed to by the ControlToValidate property

§value: The actual value entered by the user

Keep in mind that you can use whatever name you prefer; you don't need to use source and value. The ClientValidationFunction event must return a True or False condition to indicate whether validation succeeded for failed.

Run the example by launching your browser and navigating to Custom.aspx, shown in Figure 6-14.

Figure 6-14: Custom validator control example 1

For this example, the IsCardValid function expects the credit card number to be a string of all 5s. In a real-world application, you might want to add the logic to validate the credit card so that you can make sure an individual's credit card number is valid.

Enter a value that is not valid as per the IsCardValid function and then press the Tab key; your screen should appear similar to Figure 6-15.

Figure 6-15: Custom validator control example 2

Because the value you entered does not match the value in the IsCardValid function, the function returns False and your error message is displayed.

Next, enter all 5s and click the Validate button. This time, IsCardValid returns True and your message is displayed as shown in Figure 6-16.

Figure 6-16: Custom validator control example 3

As you can see, the CustomValidator control is really the catchall for all the other validation controls. When one of the other controls does not fit the bill, you can customize your validation control to roll your own validation.

Using the ValidationSummary Control

Use the ValidationSummary control to capture all the validation errors from the other controls and display them on the page as a list, a bulleted list, or in single paragraph format. The errors can be displayed inline and/or in a pop-up message box. Table 6-6 lists the properties commonly used with the ValidationSummary control.

Table 6-6: Properties of the ValidationSummary control

Property

ID

DisplayMode

Definition

This property gets or sets the identifier for the control. This identifier is used via programm ing to access the control's properties. If an identifier does not exist, then you cannot write handlers for this control.

Indicates

Соседние файлы в папке c#