Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
ASP .NET Database Programming Weekend Crash Course - J. Butler, T. Caudill.pdf
Скачиваний:
31
Добавлен:
24.05.2014
Размер:
3.32 Mб
Скачать

Session 11—Validating User Input

103

messages at the point on the page where the validation control is inserted. Additionally, the output can be streamed as HTML or in plain text. This is controlled by the display property of each control. The display property can be set to static, dynamic, or none.

By setting the display property to static, the validation control will allocate an appropriate amount of space on your Web page so that when the error message is displayed, the layout of the page doesn’t change.

By setting the display property to dynamic, the validation control will not reserve space on the HTML page for the error message. Therefore, when the error message is displayed, form elements may be moved around to accommodate the error message and thus disrupt the desired look of your form.

By setting the display property to none, no message will be displayed immediately next to the validated control. Why would you ever use this setting? In some situations you may choose to display all validation errors in a consolidated area of the page or in a single message box for the user. In this case you can use the ValidationSummary control to display a summarized list of all error messages rather than displaying them individually next to each control.

Type Property

When comparing values in controls, the values must be of the same type, and you typically will need to explicitly tell the validation control the types being compared. The following type property enumerators are valid: String, Integer, Double, DateTime, and Currency.

Operator Property

When comparing values, the options available for doing the comparison include:

Equal, NotEqual, GreaterThan, GreaterThanEqual, LessThan, LessThanEqual, and DataTypeCheck.

These operator properties are relatively intuitive except for DataTypeCheck, which simply evaluates if the values being compared are of the same data type, for instance, that both are strings or integers.

Using Validation Controls

The following examples are all included in the Session 11 folder on the CD. We will look at a single example page for using each of the validation controls.

Let’s look at a page that captures basic user information such as the user’s name, e-mail address, password, age, and a subscription code that enables the user to subscribe to an online mailing list. Figure 11-1 illustrates the results of using the validation controls to validate required fields, meet regular expression conditions, and to validate field values and types.

104

Saturday Afternoon

Figure 11-1 Use of validation controls

RequiredFieldValidator

The first thing that you will need to do is insure that the user has at least attempted to complete certain fields. In our example, the only required field is the Full Name field. In order to validate that a user enters information in the Full Name field, you simply insert a RequiredFieldValidator control next to the field you want to validate as shown in Listing 11-1.

Listing 11-1 Example of Using RequiredFieldValidator Control

<%@ Page Language=”vb” %> <HTML>

<HEAD>

<SCRIPT LANGUAGE=”VB” RUNAT=”server”>

Sub Page_Load(Source As Object, E as EventArgs) If Page.IsPostBack Then

lblTitle.Text = “Submit was successful”

Else

lblTitle.Text = “Leave the field blank and Submit”

End If End Sub

</SCRIPT>

</HEAD>

<BODY>

<FORM ID=”WebForm1” METHOD=”post” RUNAT=”server” NAME=”WebForm1”> <P>

Session 11—Validating User Input

105

<ASP:LABEL ID=”lblTitle” RUNAT=”SERVER” /> </P>

<P>

Full Name

<ASP:TEXTBOX ID=”txtName” RUNAT=”SERVER”></ASP:TEXTBOX> </P>

<P>

<ASP:REQUIREDFIELDVALIDATOR

ID=”valReqName”

ERRORMESSAGE=”You Must Fill In The <B>Full Name</B> Field” RUNAT=”SERVER”

CONTROLTOVALIDATE=”txtName”

BACKCOLOR=”#FFFF80”

DISPLAY=”Static”>

</ASP:REQUIREDFIELDVALIDATOR>

</P>

<P>

<ASP:BUTTON ID=”btnSubmit” RUNAT=”SERVER” TEXT=”Submit”></ASP:BUTTON> </P>

</FORM>

</BODY>

</HTML>

The ControlToValidate property has been set to the id of the control you want to validate, in this case the txtName control. Next, set the ErrorMessage property to a string. In this case, we have added some additional html tags, <B> </B> tags, to provide some bold formatting around the error message. Finally, set the Display property to Static so that the page formatting will remain consistent, regardless if a message is displayed or not.

RegularExpressionValidator

Next, you need to validate the user’s e-mail address to make sure that it meets standard Internet e-mail naming conventions. You will do this by utilizing the

RegularExpressionValidator control.

A regular expression is a very flexible method of determining if a string value meets certain requirements in terms of its use of upperor lowercase letters, range of letters, number of characters, use of integers, mix of letters, special characters, or numbers as part of a string.

For example, in the sample registration page, we have created a regular expression to ensure that the user’s e-mail conforms to standard e-mail formats. This means that it will contain a series of numbers or letters followed by @ followed by another series of numbers or letters, followed by a period and a final series of numbers or letters.

The expression that tests if the user’s input conforms to this standard is set in the property validationexpression as shown in boldface in Listing 11-2.

Listing 11-2 Implementing RegularExpressionValidator Control

<%@ Page Language=”vb” %> <HTML>

<HEAD>

<SCRIPT LANGUAGE=”VB” RUNAT=”server”>

Sub Page_Load(Source As Object, E as EventArgs)

Continued

106

Saturday Afternoon

Listing 11-2

Continued

If Page.IsPostBack Then

lblTitle.Text = “Submit was successful”

Else

lblTitle.Text = “Enter an invalid email address and Hit the Submit

button”

End If End Sub </SCRIPT>

</HEAD>

<BODY>

<FORM ID=”WebForm1” METHOD=”post” RUNAT=”server” NAME=”WebForm1”> <P>

<ASP:LABEL ID=”lblTitle” RUNAT=”SERVER” /> </P>

<P>

Email Address

<ASP:TEXTBOX ID=”txtEmail” RUNAT=”SERVER”></ASP:TEXTBOX>

<ASP:REGULAREXPRESSIONVALIDATOR

ID=”valRegEmail”

ERRORMESSAGE=”Email needs to conform to <B>user@domain.com</B>” RUNAT=”SERVER”

CONTROLTOVALIDATE=”txtEmail” VALIDATIONEXPRESSION=”[\w-]+(\+[\w-]*)?@([\w-]+\.)+[\w-]+” BACKCOLOR=”#FFFF80”

DISPLAY=”Static”>

</ASP:REGULAREXPRESSIONVALIDATOR>

</P>

<P>

<ASP:BUTTON ID=”btnSubmit” RUNAT=”SERVER” TEXT=”Submit”></ASP:BUTTON> </P>

</FORM>

</BODY>

</HTML>

All of the remaining properties are very similar to those used for the RequiredField Validator control. The extensive flexibility of the RegularExpressionValidator enables you to quickly create custom validators for a wide range of validation routines such as:

Internet URL = http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?

US Phone Number = ((\(\d{3}\) ?)|(\d{3}-))?\d{3}-\d{4}

US Social Security Number = \d{3}-\d{2}-\d{4}

US Complex Zip Code = \d{5}(-\d{4})?

CompareValidator

The CompareValidator is self-explanatory. It is used to compare the value of a user control to another user control’s value or to a defined value. As illustrated in Listing 11-3, we are using the control to make sure that the second password entered by the user matches the first password entered.

Session 11—Validating User Input

107

Listing 11-3 Using the CompareValidator Control

<%@ Page Language=”vb” %> <HTML>

<HEAD>

<SCRIPT LANGUAGE=”VB” RUNAT=”server”>

Sub Page_Load(Source As Object, E as EventArgs) If Page.IsPostBack Then

lblTitle.Text = “Submit was successful”

Else

lblTitle.Text = “Enter non-identical values and hit the Submit

button”

End If End Sub </SCRIPT>

</HEAD>

<BODY>

<FORM ID=”WebForm1” METHOD=”post” RUNAT=”server” NAME=”WebForm1”> <P>

<ASP:LABEL ID=”lblTitle” RUNAT=”SERVER” /> </P>

<P>

Password

<ASP:TEXTBOX ID=”txtPassword1” RUNAT=”SERVER” TEXTMODE=”Password”></ASP:TEXTBOX>

</P>

<P>

Re Enter Password

<ASP:TEXTBOX ID=”txtPassword2” RUNAT=”SERVER” TEXTMODE=”Password”></ASP:TEXTBOX>

<ASP:COMPAREVALIDATOR

ID=”valCompPassword”

ERRORMESSAGE=”The password fields must match each other” RUNAT=”SERVER”

CONTROLTOVALIDATE=”txtPassword2”

CONTROLTOCOMPARE=”txtPassword1”

BACKCOLOR=”#FFFF80”

DISPLAY=”Dynamic”>

</ASP:COMPAREVALIDATOR>

<ASP:REQUIREDFIELDVALIDATOR

ID=”valReqName”

ERRORMESSAGE=”You must complete values in both fields” RUNAT=”SERVER”

CONTROLTOVALIDATE=”txtPassword2”

BACKCOLOR=”#FFFF80”

DISPLAY=”Dynamic”>

</ASP:REQUIREDFIELDVALIDATOR>

</P>

<P>

<ASP:BUTTON ID=”btnSubmit” RUNAT=”SERVER” TEXT=”Submit”></ASP:BUTTON> </P>

</FORM>

</BODY>

</HTML>