• No results found

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.

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 aRequiredFieldValidatorcontrol 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>

<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 ControlToValidateproperty has been set to the id of the control you want to vali- date, in this case the txtNamecontrol. Next, set the ErrorMessageproperty 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 Displayproperty to Staticso 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

RegularExpressionValidatorcontrol.

A regular expression is a very flexible method of determining if a string value meets certain requirements in terms of its use of upper- or 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 prop- erty validationexpressionas 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

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>[email protected]</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 Validatorcontrol. The extensive flexibility of the RegularExpressionValidatorenables 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 CompareValidatoris 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.

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>

Note the boldfaced code. We have set the ControlToValidateproperty to the second password field. Once the user has entered the second password, a client-side validation will compare it against the first password field defined by the ControlToCompareproperty.

Additionally, we have set the Typeproperty of the comparison to Stringto insure that when the Operatorproperty Equalis applied that the comparison will work correctly. As already mentioned, you could use any number of operator enumerators to do the comparison as well as any of the property enumerators.

If we wanted to compare a value rather than two controls, you could simply set the ValueToCompareproperty to a specific string rather than use the ControlToCompare property.

RangeValidator

This control is useful to compare one control to values of two other controls or to a specific range. In Listing 11-4, we are simply checking to see if the user has entered a valid age range of equal or greater than 18 but less than or equal to 50 years old.

Listing 11-4 Using a RangeValidator 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 an age <18 or >50 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> Age

<ASP:TEXTBOX ID=”txtAge” RUNAT=”SERVER” HEIGHT=”24” WIDTH=”28”></ASP:TEXTBOX>

<ASP:RANGEVALIDATOR ID=”RangeValidator1”

ERRORMESSAGE=”You must be older than 18 and less than 50 to register” RUNAT=”SERVER” CONTROLTOVALIDATE=”txtAge” BACKCOLOR=”#FFFF80” MINIMUMVALUE=”18” TYPE=”Integer” MAXIMUMVALUE=”50”> </ASP:RANGEVALIDATOR>

</P> <P>

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

</FORM> </BODY> </HTML>

Most of the properties on this control we have used in the previous examples. The new property, in boldface, of MinimumValueestablishes the minimum range of the compare. MaximumValueestablishes the upper range of the comparison. If you wanted to utilize the values of other controls, you could use the properties MaximumControland MinimumControl, setting the values equal to the id’s of the controls you want to compare against.

Several factors for this control should be noted. If the user leaves a control blank, the control passes the range validation. To force the user to enter a value, add a RequiredField validation control as well. If both MaximumControland MaximumValueare specified, then the MaximumControlis used. If both MinimumControland MinimumValueare specified, then MinimumControlwill be used to perform the range validation.

CustomValidator

Although the above controls should cover 90 percent of your validation needs, there will be scenarios where you will want to take a value the user enters, apply an algorithm, compare it to a database value, or run it against a Web service to determine if the information is valid. In these cases, you can utilize the CustomValidator control. This control enables you to define both client- and server-side validation routines to compare a control value against. These functions must return Boolean trueor falseto process the appropriate error mes- sage for the control.

For the current example, you are going to compare a subscription code provided by the user against a fixed value. Listing 11-5 illustrates how you can utilize a custom server-side function and a custom client-side function to perform validation.

In Listing 11-5, we have created a server-side function ValidateSubscriptionServer that simply accepts the control value as a string and sets objArgs.IsValidequal to trueor falsedepending upon the result. In this case, you simply check to see if the user control you are validating has a text value equal to abc123. However, you could have also performed a database query or any other type of routine to do the comparison.

Next, we have included a client-side validation routine. The routine is a Javascript 1.0- compliant function called ValidateSubscriptionClientthat runs on the client side. Since this function does not have the RunAt = Serverattribute, it can have the same name as our server-side function, but will be processed as soon as a user moves their mouse from the Subscription Code field.

Listing 11-5 Using a CustomValidator Control

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

<HEAD>

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

Continued

Listing 11-5 Continued

Sub Page_Load(Source As Object, E as EventArgs) End Sub

Public Sub ValidateSubscriptionServer(objsource As Object, objArgs As ServerValidateEventArgs)

If strComp(objArgs.Value, “abc123”, CompareMethod.Text) = 0 Then objArgs.isValid=True

lblTitle.Text = “Subscription value accepted on client and server!” Else

objArgs.isValid =False

lblTitle.Text = “Subscription value rejected on server!” End If End Sub </SCRIPT> <SCRIPT LANGUAGE=”javascript”> function ValidateSubscriptionClient(objSource,objArgs) { if(objArgs.Value==”abc123”) { objArgs.IsValid= true; } else { objArgs.IsValid=false; } return; } </SCRIPT> </HEAD> <BODY>

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

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

<P>

Subscription Code

<ASP:TEXTBOX id=”txtSubscription” RUNAT=”SERVER”></ASP:TEXTBOX>

<ASP:CUSTOMVALIDATOR id=”CustomValidator1” RUNAT=”SERVER” ONSERVERVALIDATE=”ValidateSubscriptionServer” CLIENTVALIDATIONFUNCTION=”ValidateSubscriptionClient” BACKCOLOR=”#FFFF80”

CONTROLTOVALIDATE=”txtSubscription”

ERRORMESSAGE=”This Subscription Code is Not Valid”> </ASP:CUSTOMVALIDATOR>

</P> <P>

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

</FORM> </BODY> </HTML>

To bind these functions to the Web form, you simply insert a CustomValidator control and set two new properties ClientValidationFunctionand OnServerValidate.

In the previous example we have decided to use a server-side function as part of our validation, and set the OnServerValidateproperty equal to the server-side function ValidateSubscriptionServer. We also have enabled a client-side function, by setting the ClientValidationFunctionproperty equal to the client side function, ValidateSubscriptionClient.

ValidationSummaryx

The last control that is useful for validation is the ValidationSummarycontrol. This control provides you with the option of listing all of the validation errors in a consolidated list for the user, rather than displaying each error message next to the field where the error actually occurred. To use the control, simply plug a ValidationSummarycontrol somewhere on the page your user is likely to reference when reviewing problems with validation:

<ASP:VALIDATIONSUMMARY ID=”valSummary” SHOWMESSAGEBOX=”False” DISPLAYMODE=”List”

HEADERTEXT=”Please correct the following errors.” SHOWSUMMARY=”True”

RUNAT=”SERVER”> </ASP:VALIDATIONSUMMARY>

The control will automatically display all relevant validation errors in a consolidated area on the page. If you do not want the individual control errors to display, you will need to set each validation control ErrorMessageproperty to an empty string. Setting the ShowSummaryproperty to False, will prevent the display of each control’s error message. Instead, only the content of the HeaderTextproperty will be shown.

In addition, you can choose to display error messages in a pop-up message box by setting the ShowMessageBoxproperty of the ValidationSummarycontrol to True. Be aware that this will only work properly when used in Internet Explorer 4.0 or higher.

The DisplayModeproperty can be set to List, BulletList, or SingleParagraphto modify the manner in which the list of errors is handled.

R

EVIEW

With the use of these controls, you should now be able to eliminate a tremendous amount of client- and server-side validation code previously required when developing ASP pages. Additionally, the ability to construct your own client- and server-side validation controls should provide you with all the flexibility you need to handle 90 percent of your business requirements.

Q

UIZ

Y

OURSELF

1. When constructing a custom control with custom client-side validation, what client-side language and version should you utilize? (See “Common Aspects of Validation Controls.”)

2. What standard ASP.NET validation controls can be combined to perform a value type and value range check on a text field? (See “CompareValidator” and “RangeValidator.”)

3. What are the performance impacts of including <%@ Page ClientTarget = “DownLevel” %>in pages with validation controls? (See “Common Aspects of Validation Controls.”)

Session Checklist

Understanding the differences between in-process and out-of-process state

maintenance