Lesson 2: Validating Data

Lesson 2: Validating Data

One of the most important steps in getting data entries from a user is ensuring that the data is valid. Validity is determined by a number of criteria: Did the user enter anything? Is the entry the appropriate kind of data (a telephone number, for example)? Is the data within a required range?

ASP.NET provides validation controls to help you check Web form data entries against these and other criteria before the data items are accepted. This lesson teaches you how to use the validation controls to catch invalid data and direct the user to fix the problems that occur.

After this lesson, you will be able to

  • Explain how ASP.NET checks validity, including why it checks validity both on the client side and on the server side

  • Validate data entries in a TextBox control using one or more criteria

  • Display error messages to help users correct data validation problems on a Web form

  • Cancel validation to allow the user to exit from a Web form that has validation errors

  • Create custom validation criteria to be evaluated on the server or client, or both

Estimated lesson time: 40 minutes

Using Validation

The validation controls check the validity of data entered in associated server controls on the client before the page is posted back to the server. This is an important improvement to previous validation schemes most validity problems can be caught and corrected by the user without a round-trip to the server.

Client-side validation is provided by a JScript library named WebUIValidation.js, which is downloaded separately to the client. Although JScript is widely supported, the Document Object Model (DOM) that the library relies on is available only in Microsoft Internet Explorer version 4.0 and later. Therefore, validation controls also automatically provide server-side validation. Server-side validation is always performed, whether or not client-side validation has occurred. This double-checking ensures that custom validations are performed correctly and that client-side validation has not been circumvented.

The validation controls check the value of the server control specified in their ControlToValidate property. Table 4-6 describes the six validation controls.

Table 4-6. ASP.NET Validation Controls

Validation control

Use to

RequiredFieldValidator

Check whether a control contains data

CompareValidator

Check whether an entered item matches an entry in another control

RangeValidator

Check whether an entered item is between two values

RegularExpressionValidator

Check whether an entered item matches a specified format

CustomValidator

Check the validity of an entered item using a client-side script or a server-side code, or both

ValidationSummary

Display validation errors in a central location or display a general validation error description

To use the validation controls, follow these steps:

  1. Draw a validation control on a Web form and set its ControlToValidate property to the control you want to validate. If you re using the CompareValidator control, you also need to specify the ControlToCompare property.

  2. Set the validation control s ErrorMessage property to the error message you want displayed if the control s data is not valid.

  3. Set the validation control s Text property if you want the validation control to display a message other than the message in the ErrorMessage property when an error occurs. Setting the Text property lets you briefly indicate where the error occurred on the form and display the longer ErrorMessage property in a ValidationSummary control.

  4. Draw a ValidationSummary control on the Web form to display the error messages from the validation controls in one place.

  5. Provide a control that triggers a postback event. Although validation occurs on the client side, validation doesn t start until a postback is requested.

Figure 4-16 shows simple validation being performed on a Web form.

figure 4-16 validation on a web form

Figure 4-16. Validation on a Web form

Figure 4-17 shows validation using a ValidationSummary control. Notice that the individual validators display their Text properties, whereas the longer ErrorMessage property is displayed in the ValidationSummary control.

figure 4-17 using the validationsummary control

Figure 4-17. Using the ValidationSummary control

To display validation errors as a dialog box, set the ValidationSummary control s ShowMessage property to True. You can see the result in Figure 4-18.

figure 4-18 the validation errors dialog box

Figure 4-18. The validation errors dialog box

TIP
Use the RequiredFieldValidator control s InitialValue property to ignore instructions included in the control to validate. For example, if the control to validate is a DropDownList that includes an item in with the text Select an item, enter Select an item in the RequiredFieldValidator control s InitialValue property to make that selection invalid.

Combining Validations

A server control can have multiple validators. For instance, a TextBox control for a telephone number might be both a required field and a regular expression, so the TextBox would be checked by two validation controls, as shown in Figure 4-19.

figure 4-19 multiple validators

Figure 4-19. Multiple validators

To write meaningful error messages when more than one validation control checks a single control, you need to understand the ASP.NET validation rules. These rules might not make obvious sense, but they make it possible to write error messages that address specific problems.

For example, all validation controls except the RequireFieldValidator control are considered valid if they are blank. This makes it possible to provide one error message if the control is blank, using the RequiredFieldValidator control, and a different error message if the control is out of range or not in the appropriate format, as shown in the telephone number example in Figure 4-19.

The rules listed in Table 4-7 apply to data conversion for the CompareValidator control.

Table 4-7. CompareValidator Validation Rules

If the value from the control

The result is

Specified in the ControlToValidate property can t be converted to the appropriate data type

Invalid

Specified in the ControlToCompare property can t be converted to the appropriate data type

Valid

In the second case in Table 4-7, you should provide a separate validation control for the control specified in the ControlToCompare property to make sure value entered in the control is the appropriate data type.

Canceling Validation

Because validation occurs before the server processes the page, a user can become trapped by validation unless you provide a way to cancel validation without posting back.

To let the user cancel validation, provide a Submit HTML control that sets the Page_ValidationActive attribute, as shown in boldface in the following HTML code:

<INPUT  onclick="Page_ValidationActive=false;" style="Z INDEX : 114; LEFT: 386px; WIDTH: 62px; POSITION: absolute; TOP: 130px; HEIGHT: 30px" type="submit" value="Cancel">

The preceding button definition cancels validation and posts the page back to the server. You can determine whether the user has cancelled the operation by checking the Page object s IsValid property in the Page_Load event procedure. You have to revalidate the page because canceling validation sets IsValid to True. The following code shows how to check whether the user cancelled validation:

Visual Basic .NET

Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' Validate in case user cancelled validation. If Page.IsPostBack Then Page.Validate() ' Check if page is valid. If Not Page.IsValid Then ' User cancelled operation, return home. Response.Redirect("default.htm") End If End Sub

Visual C#

private void Page_Load(object sender, System.EventArgs e) { // Validate in case user cancelled validation. if (Page.IsPostBack) { Page.Validate(); if (!Page.IsValid) // User cancelled validation. Response.Redirect("default.htm"); } }

Customizing Validation

To perform complex types of validation not provided by the standard validation control, use a CustomValidator control and write code to perform the validation on the server side and (optionally) on the client side.

On the server side, place your validation code in the ServerValidate event procedure. The arguments to this procedure provide access to the control to validate. The following event procedure validates that an entered number is prime:

Visual Basic .NET

' Validate a prime number. Private Sub CustomValidator1_ServerValidate _ (ByVal source As System.Object, ByVal args As _ System.Web.UI.WebControls.ServerValidateEventArgs) _ Handles CustomValidator1.ServerValidate Try Dim iPrime, iCount As Integer ' Get value from ControlToValidate (passed as args) iPrime = Integer.Parse(args.Value) For iCount = 2 To iPrime \ 2 ' If number is evenly divisible, it's ' not prime, return False. If iPrime Mod iCount = 0 Then args.IsValid = False Return End If Next ' Number is Prime, return True. args.IsValid = True Return Catch ex As Exception ' If there was an error parsing, return False. args.IsValid = False Return End Try End Sub

Visual C#

private void vldtxtPrime_ServerValidate(object source, System.Web.UI.WebControls.ServerValidateEventArgs args) { try { // Get value from ControlToValidate (passed as args). int iPrime = Int32.Parse(args.Value); for (int iCount = 2; iCount <= (iPrime / 2); iCount++) { // If number is evenly divisible, it's // not prime,return False. if((iPrime % iCount) == 0) { args.IsValid = false; return; } // Number is prime, return True. args.IsValid = true; return; } } catch(Exception e) { // If there was an error parsing, return False. args.IsValid = false; return; } }

To provide client-side validation, specify a validation script in the CustomValidator control s ClientValidationFunction property. Client-side validation is optional, and if you provide it, you should maintain similar validation code in both places. The following script provides a client-side version of the prime number validation performed on the server:

VBScript

<script language="vbscript"> Sub ClientValidate(source, arguments) For iCount = 2 To arguments.Value \ 2 ' If number is evenly divisible, it's ' not prime, return False. If arguments.Value Mod iCount = 0 Then arguments.IsValid = False Exit Sub End If Next arguments.IsValid = True End Sub </script>

JScript

<script language="jscript"> function ClientValidate(source, arguments) { for (var iCount = 2; iCount <= arguments.Value / 2; iCount++) { // If number is evenly divisible, // it's not prime. Return false. if ((arguments.Value % iCount) == 0) { arguments.IsValid = false; return false; } } // Number is prime, return True. arguments.IsValid = true; return true; } </script>



MCAD(s)MCSD Self-Paced Training Kit(c) Developing Web Applications With Microsoft Visual Basic. Net and Microsoft V[.  .. ]0-315
MCAD(s)MCSD Self-Paced Training Kit(c) Developing Web Applications With Microsoft Visual Basic. Net and Microsoft V[. .. ]0-315
ISBN: N/A
EAN: N/A
Year: 2003
Pages: 118

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net