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

Microsoft Visual C++ .NET Professional Projects - Premier Press

.pdf
Скачиваний:
180
Добавлен:
24.05.2014
Размер:
26 Мб
Скачать

530 Project 4 CREATING A MANAGED EXTENSIONS CLASS LIBRARY

{

}

</script>

Now that you are familiar with the properties, methods, and events of Web controls, you are ready to learn how to add validation controls to the forms.

Validation Controls

For certain fields, you might want to make sure that the data entered by the user

is in the specified format. For example, you might want to ensure that the user can

 

 

Y

enter only numeric data in the Age field. In such situations, you can add valida-

 

L

 

F

M

 

tions to the control. Validations ensure that data entered for a control is checked

with certain predefined conditions.

 

 

A ASP.NET has six validationEcontrols, listed next, that you can use to validate the

data entered by theTuser. ll of these validation controls are inherited from the BaseValidator class. he BaseValidator class is an abstract class. As a result, you can use this class to implement other validation controls in addition to the existing validation controls.

RequiredFieldValidator. Used to validate a control to check whether it is empty.

CompareValidator. Used to compare values in different controls to check if the two values match.

RangeValidator. Used to check if the value in a control is in the predefined text or numeric range.

ValidationSummary. Used to display all the validation error messages grouped together.

RegularExpressionValidator. Used to check if the value in a control matches a specified regular expression.

CustomValidator. Used to perform validation on a control by using user-defined functions.

ValidationSummary. Used to display all the validation error messages grouped together.

Now that you know about the validators that form a part of the BaseValidator class, you likely want to know how exactly validators work. This can be explained by dividing the process into four steps:

Team-Fly®

INTRODUCTION TO ASP.NET

Chapter 15

531

 

 

 

 

1.You add a validation control.

2.You associate the validator control with another control that requires validation.

3.Validation controls validate the values entered in the controls.

4.After the validation is complete, the value for the IsValid property of each validation control attached to the control is set to either True or False. If the value is True, the validation succeeded. If the value is

False, the validation failed. After all the validations have succeeded, the page data is processed at the server.

Using Validation Controls

Before you add validation controls, you need to create an ASP.NET Forms page that contains controls whose data you want validated. To do this, you need to design a basic form that accepts user input. To begin with, you’ll create a project named SampleValidation and a form named CheckOut. The form should accept the necessary information from a user issuing a book from a library. Specify the properties in Table 15-5 to the controls on your form.

Table 15-5

Sample Form Control IDs

 

Control

Contains

ID

 

 

 

Button

Accept

AcceptButton

Label

Message

MessageLabel

TextBox

Confirm Password

ConfirmBox

TextBox

Member Card Number

MemberNumberBox

TextBox

Number of Books

NumberOfBooksBox

TextBox

Password

PasswordBox

TextBox

Telephone Number

TelephoneNumberBox

TextBox

User Name

UserNameBox

 

 

 

Now that your form is ready, it’s time to learn about the other validation controls. In the next section, you’ll learn about the RequiredFieldValidatator control.

532 Project 4 CREATING A MANAGED EXTENSIONS CLASS LIBRARY

RequiredFieldValidator

This control, as its name suggests, checks if the user has entered some data for the field. If the user leaves the field empty, an exception is raised. To add this control to the form, drag the RequiredFieldValidator control from the Toolbox to the form. Table 15-6 displays the values set for properties of this validation control.

Table 15-6 Setting Properties for the RequiredFieldValidator Control

Property

Value

ID

UserNameRequiredFieldValidator

ControlToValidate

UserNameBox

ErrorMessage

Enter your user name.

Display

Dynamic

 

 

After you add the RequiredFieldValidator control, you can set its properties. After setting the properties, you need to add the following code to the ASPX file for the Click event of the Accept button:

private void Accept_Click(object sender, System.EventArgs e)

{

if(Page.IsValid == true)

{

MessageLabel.Text = “Welcome “ + UserNameBox.Text; //This makes the label visible MessageLabel.Visible = true;

}

}

If the user does not enter any data in the User Name text box, then the application will raise an exception error.

CompareValidator

The CompareValidator control is used to compare the values entered in different controls. You can compare the values by using operators, such as Equal, NotEqual, GreaterThan, and LessThan. In ASP.NET, you can compare values of different data types, such as String, Integer, Double, Date, and Currency. Table 15-7 lists the common properties of the CompareValidator control.

 

INTRODUCTION TO ASP.NET

Chapter 15

533

Table 15-7 Properties of the CompareValidator Control

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Property

Description

 

 

 

 

 

 

 

 

 

ControlToCompare

Used to get or set the ID of the control with the value that you

 

 

want to compare.

 

 

 

 

ControlToValidate

Used to get or set the ID of the control with the value that you

 

 

want to validate.

 

 

 

 

Display

Used to get or set values such as Static, Dynamic, or None. The

 

 

default value is Static.

 

 

 

 

ErrorMessage

Used to set the text that will appear in the error message.

 

Operator

Used for the comparison. The value for this property can be

 

 

Equal, NotEqual, LessThan, or GreaterThan. The default value

 

 

is Equal.

 

 

 

 

Type

Specifies the data type of the value that you want to compare.

 

 

This property can possess String, Integer, Currency, Date, or

 

 

Double values. The default value is String.

 

 

 

 

ValueToCompare

Used to get or set a specific value that you want to compare.

 

 

 

 

 

 

 

Now that you are familiar with the properties of the CompareValidator, you’ll add the CompareValidator control in the checkout form. To do so, we will compare the values entered in the Password_Box and Confirm_Box text boxes. However, before doing so, you need to add the ControlValidator control to the form. To add the control, use the following code:

<asp:CompareValidator

id = “PasswordValidator” runat = “server” ControlToCompare = “Password_Box” ControlToValidate = “Confirm_Box” ErrorMessage = “Please retype the password.” Display = “Dynamic”>

</asp:CompareValidator>

Then you need to edit the code for the Click event of the Accept button. To do so, edit the code as shown here:

private void Button1_Click(object sender, System.EventArgs e)

{

if( Page.IsValid == true)

534 Project 4 CREATING A MANAGED EXTENSIONS CLASS LIBRARY

{

//This is used to set a message to be displayed on the label MessageLabel.Text = “Welcome “ + UserNameBox.Text + “, You are authorized

to use the services provided by the library.”; //This is used to make the label visible

MessageLabel.Visible = true;

}

To check whether the ControlValidator is functioning properly, enter different values in the Password_Box and Confirm_Box password text boxes. An error message will appear if the entered values don’t match.

RangeValidator

A RangeValidator control checks whether the value entered in the control falls within the predefined range. You can use the RangeValidator to specify a minimum as well as a maximum range. The RangeValidator control can possess the following properties:

MaximumValue. Used to set the upper-limit value for the validation range.

MinimumValue. Used to set the lower-limit value for the validation range.

Type. Used to set the data type for the values that will be compared.

Now look at an example of the CheckOut form. You’ll validate the BooksNumber text box, which accepts the number of books that are issued to an individual. You’ll set the validation rule to allow the maximum number of books to be issued to a person to be five. To implement this, set the properties of the RangeValidator control as shown in Table 15-8.

Table 15-8 Setting the Properties of the RangeValidator Control

Property

Value

ID

BooksRangeValidator

ControlToValidate

BooksNumberBox

MaximumValue

5

MinimumValue

1

Type

Integer

 

INTRODUCTION TO ASP.NET

Chapter 15

535

 

 

 

 

 

 

 

 

 

 

 

 

Property

Value

 

 

 

 

 

 

 

 

 

ErrorMessage

The number of books must be between 1 and 5.

Display

Dynamic

 

 

 

 

 

 

 

 

 

 

RegularExpressionValidator

You can validate a value entered in a control with respect to an expression by using the RegularExpressionValidator control. The expression that you compare with can be an expression, such as a telephone number, ZIP code, social security number, or e-mail address.

The RegularExpressionValidator control uses the ControlToValidate, ErrorMes-

sage, and Display properties. It also uses a property called ValidationExpression to validate user input data against some pattern of a specific expression.

You’ll now use this validation in the CheckOut form. You can implement this validation for the TelephoneNumber text box. You need to validate this number against a fixed pattern of U.S. telephone numbers. In addition, the different parts of the telephone number must be separated by hyphens.

You can add the RegularExpressionValidator control by using the Toolbox. The properties set for the control are displayed in Table 15-9.

Table 15-9 Setting the Properties of the RegularExpressionValidator Control

Property

Value

ID

TelephoneRegularExpressionValidator

ControlToValidate

TelephoneNumberBox

ValidationExpression

[0-9]{3}-[0-9]{3}\s[0-9]{4}

ErrorMessage

Please retype the telephone number.

Display

Dynamic

 

 

The ValidationExpression property contains the value [0-9]{3}-[0-9]{3}\s[0- 9]{4}, which breaks down as follows:

[0-9] represents any digit between 0 and 9.

{3} indicates that three digits are required for the first part.

536Project 4 CREATING A MANAGED EXTENSIONS CLASS LIBRARY

A hyphen is placed to indicate that the hyphen is required.

\s indicates that a space is required. This means that the next three digits are followed by a space.

[0-9]{4} indicates a four-digit number in which each number is in the range of 0 to 9.

To verify that the application is working properly, enter a telephone number that does not match the specified pattern. You will encounter an error message.

CustomValidator

The CustomValidator control is used to validate a value entered in a control by using a user-defined function. For example, you can validate a control to accept only odd numbers. This is possible by writing code for detecting an odd number. Therefore, you can use the CustomValidator control.

This control enables you to use validation functions at the client side as well as the

server side. The CustomValidator control uses the ClientValidationFunction

property to get or set the client script function, which is called automatically to validate the control. To write the validation code, you can use any scripting language, such as JavaScript or VBScript.

For server-side validation, the CustomValidator control raises the ServerValidate event. You must write code in the event handler for this control. You can do this by using either the code-behind file or HTML view of the ASPX file.

Next, you will implement the CustomValidator control in the CheckOut form. You can use this validation control to validate the MemberNumberBox text box. You can add the CustomValidator control to the CheckOut form. Table 15-10 displays the values set for the properties used in the CustomValidator control.

Table 15-10 Setting the Properties of the CustomValidator Control

Property

Value

ID

NumberCustomValidator

ControlToValidate

MemberNumberBox

ClientValidationFunction

ClientIsValidCard

ErrorMessage

This is an invalid card number, please retype.

Display

Dynamic

 

 

Valida-

INTRODUCTION TO ASP.NET

Chapter 15

537

 

 

 

 

In the preceding table, the value for the ClientValidationFunction property is set to ClientIsValidCard. This function will be invoked when the control with ID MemberNumberBox is validated. We can write this function using VBScript as shown here:

<script language=”vbscript”>

Sub ClientIsValidCard(source,arguments)

if(arguments.Value)=”KBL77777” Then

arguments.IsValid=true Else

arguments.IsValid=false End If

End Sub </script>

In the preceding code:

The ClientIsValidCard function accepts two parameters, source and argument.

The argument parameter contains the actual information about the value being entered in the control. Therefore, in the following function, the value entered in the control with the ID MemberNumberBox is matched against a value.

If the two values match, the IsValid property is set to True.

If the value of the function is returned as True, the validation succeeds.

To verify that the code is functioning properly, enter an incorrect value in the MemberNumberBox text box. You will encounter an error message.

ValidationSummary

You can display all prevailing errors in a page by using the ValidationSummary control. The error on the page can be displayed in a list, bulleted list, or paragraph format. In addition, you can display the summary of errors inline or as a pop-up message box. Table 15-11 lists some of the common properties of the

tionSummary control.

538

Project 4

CREATING A MANAGED EXTENSIONS CLASS LIBRARY

 

 

 

 

 

 

Table 15-11 Properties of the ValidationSummary Control

 

 

 

 

 

 

Property

Description

 

 

 

 

 

 

DisplayMode

Used to get or set the display mode of the validation summary.

 

 

 

 

This property accepts one of the three values: List, BulletList, or

 

 

 

 

SingleParagraph.

 

 

HeaderText

Used to get or set the text to be displayed at the top of the valida-

 

 

 

 

tion summary.

 

 

ShowSummary

Used to get or set a Boolean value that indicates whether the vali-

 

 

 

 

dation summary is displayed inline. The default value is True.

 

 

ShowSummaryBox

Used to get or set a Boolean value that indicates whether the vali-

 

 

 

 

dation summary is displayed as a pop-up message box. The

 

 

 

 

default value is False.

 

 

 

 

 

You can implement the ValidationSummary control in the CheckOut form by using the Toolbox. The ASP.NET code for the control is as shown here:

<asp:ValidationSummary

id=”ValidationSummary1” runat=”server”

HeaderText=”The following errors were encountered”>

</asp:ValidationSummary>

To display the validation summary as a pop-up message box, set the value of the

ShowSummaryBox property to True.

By now, you know how to use different validation controls. However, in some applications, you need a control that checks for multiple conditions. In the next section, you’ll learn about using multiple validation controls.

Using Multiple Validation Controls

It is quite easy to use multiple validation controls for the same control. You simply have to add the validation controls that you require for the control to the form, and then set the ControlToValidate property of all the validation controls as the ID of the control you want to validate.

Consider an example. Suppose you want the value of a control to be in a specific range. In addition, you require that the value of the control pass a custom validation test. For testing multiple conditions for a control’s value, you need to associ-

INTRODUCTION TO ASP.NET

Chapter 15

539

 

 

 

 

ate multiple validation controls to a single control. To do so, you use the RequiredFieldValidator control in combination with other validation controls.

Now consider the CheckOut form example again. If a user does not enter any value in the two password boxes and clicks the Accept button, the comparison validation test does not fail, because there is no value in the password boxes for the validators to validate. To avoid such a situation, you need to use the RequiredFieldValidator control in conjunction with the CompareValidator control.

Table 15-12 displays the values you need to associate for the CheckOut form. These values are used to add multiple validations to the form.

Table 15-12 Setting Properties of a Second RequiredFieldValidator Control

Property

Value

ID

PasswordRequiredFieldValidator

ControlToValidate

ConfirmBox

ErrorMessage

Enter your password

Display

Dynamic

 

 

If you don’t enter the value for the two password fields and submit the form, a message stating “Enter your password” will be displayed.

Summary

This chapter covered the basic concepts of ASP.NET and the platform requirements for ASP.NET applications. It also covered details of the ASP.NET architecture and introduced Web Forms. Finally, it covered the different types of server controls and validation controls that you can use in your page.