Validating User Input

function OpenWin(url, w, h) { if(!w) w = 400; if(!h) h = 300; window.open(url, "_new", "width=" + w + ",height=" + h + ",menubar=no,toobar=no,scrollbars=yes", true); } function Print() { window.focus(); if(window.print) { window.print(); window.setTimeout('window.close();',5000); } }
Team-Fly    

Special Edition Using Microsoft® Visual Basic® .NET
By Brian Siler, Jeff Spotts
Table of Contents
Chapter 19.  Web Controls


In addition to accepting input, validating that input is an important function of a data entry program. A typical data entry form contains validation code that must execute successfully before the information can be committed to the database. If the validation tests do not pass, then the program displays a message requesting that the user correct the erroneous data. When you build a form, certain types of controls do not require much or any validation code. For example, in a drop-down list the user is restricted to selecting a fixed set of choices that you, the programmer, control. However, a text box control allows the end user to enter almost any type of numeric or character data. Therefore, more stringent validation logic must be used before committing a text box value to the database. To aid in the process of validating user input on the Web, the .NET Framework provides several Validator classes, which are available for use on a Web form as the following controls:

  • RequiredFieldValidator Checks whether a user has entered a value in a field

  • CompareValidator Performs an equal, a greater, or a less than between two fields or a field and a value

  • RangeValidator Determines whether a value falls within a specified range

  • RegularExpressionValidator Validates that a field value matches a regular expression

  • CustomValidator Allows you to add custom code to determine the validity of an input field

  • ValidationSummary Combines the error messages from multiple validation controls

The main purpose of validation controls is to simplify the process of checking for and informing the user of invalid data. When designing a Web form, validators appear as labels that contain the validation error message. They are typically placed near the field with which they are associated, as shown in Figure 19.7.

Figure 19.7. Validator controls are special labels, which automatically display error messages if an associated field does not pass a validation test.

graphics/19fig07.gif

Performing Basic Validation

To demonstrate the ease with which you can use Validator controls in a Web application, we will create a simple example with several text box fields. Ultimately, your example will look like Figure 19.7. To begin, create a new Web application and set up the Web form as follows:

  1. Set up six TextBox controls with the following names: txtFirstName, txtLastName, txtAge, txtEMail, txtInventory, and txtUnitsSold.

  2. Delete the default text in the Text properties of each text box so that the initial text in each of them is blank.

  3. Place a Label control to the left of each text box to describe the text box.

  4. Place a Button control at the bottom of the form. Set its Text property to Save and its Name property to btnSave.

Now that we have set up a basic data entry form, we will add validation controls to each field. As you will see, using the validator controls is very easy; simply set a few properties to control the error message text, associated field, and any other inputs needed for the validation test.

Checking for Required Fields

You may have seen examples of required fields when filling out forms in real life. For example, if you leave the dollar amount on a check blank, the bank will not know how much money to withdraw. Similarly, our sample Web form contains fields for last and first name that we do not want the user to leave blank. To add required field validation for the name fields, perform the following steps:

  1. Add two RequiredFieldValidator controls to your form.

  2. Position one validator control to the right of the txtFirstName and txtLastNametext boxes.

  3. Set their Name properties to valLastName and valFirstName.

  4. Using the Properties window, set the ErrorMessage property of each control to last/first Name Field Cannot be left blank.

  5. Also in the Properties window, find the ControltoValidate property, which will display a drop-down list of the validateable controls on the form. Set this property to the name of the text box to the immediate left of each validator control.

Now, run the program and click the Save button, without entering any text in the last name or first name field. The error message you specified earlier should automatically appear when the page is refreshed.

Validating Input Ranges

In addition to determining whether there is any input in a given field, sometimes you also want to make sure the input falls within a specified range of values. The age field on our sample form is a good example. Although the back-end database would probably not allow character values in a numeric field, there still may be numeric values for age that the database would accept but are not valid; 1,000 for example. Setting up a RangeValidator control is almost as easy as using the RequiredFieldValidator; the only additional step is setting a few more properties to control the range value.

To set up a range validation for our sample form do the following:

  1. Place a RangeValidator control on the form to the right of the txtAgetext box.

  2. Set its Name property to valAge.

  3. Enter the following lines of code in the Page_Load event:

     valAge.ControlToValidate = "txtAge"  valAge.ErrorMessage = "Age must be between 1-120"  valAge.Type = ValidationDataType.Integer  valAge.MinimumValue = 1  valAge.MaximumValue = 120 

Although you could have easily used the Properties window to configure the control, the previous code sample demonstrates how to configure the control programmatically by setting properties at runtime. To specify a range for the validation test, you need to set the MinimumValue, MaximumValue, and Type properties. The sample code causes the control to check the value of the txtAge field to determine if it falls between the range of 1 and 120.

Note

Setting the Type property to let the RangeValidator control know what data type you are using is very important because strings and integers are ordered differently. For example, in the domain of strings 2 is not in the range between 1 and 120 as is the case with integers.


Comparing Field Values

Another useful validation control is the CompareValidator. A compare validator can perform a basic mathematical comparison between a text box value and a comparison value, such as determining whether the text box value is greater than or equal to the comparison value. It can also validate a field's data type.

As with the other validation controls, you need to set the associated text box name using the ControltoValidate property. To set up the type of comparison, set the Operator and Type properties. Next, you need to identify the comparison value according to the following rules.

  • If you are comparing the values in two text boxes, set the ControltoCompare property to the name of the second text box. Do not set the ValuetoCompare property.

  • If you are validating the value of a text box against a literal value, set the ValuetoCompare property to this value. Do not set the ControltoCompare property.

  • If you are validating the text box data type, you do not need to set either of the preceding properties. It is only necessary to set the Type and ControltoValidate properties.

The comparison can be thought of like an expression in an If statement, with the ControltoValidate value on the left, followed by the operator, followed by the comparison value. If the expression evaluates to True, the validation succeeds. Using this knowledge, return to the sample program and set up a validation alert that checks to make sure the value of txtUnitsSold is less than or equal to the value of txtInventory.

Note

The CompareValidator control considers an empty text box control to be valid. You can of course use a RequiredFieldValidator control on the same text box to check for this condition.


Validating an Entire Page

You already know that using validator controls enables you to alert the user of invalid data, but your code still has to make the final decision to commit the data from the form. Each validator control has an IsValid property, which is set to True if its validation test succeeded. The IsValid property of the Page object can be used to check all your validator controls in one fell swoop:

 Private Sub btnSave_Click(ByVal sender As System.Object, _          ByVal e As System.EventArgs) Handles btnSave.Click          If Page.IsValid Then              Call YourSaveDataFunction()              Response.Redirect("http://www.vbinsider.com")          End If  End Sub 

The previous code sample calls the save function and moves to a new page only if the Page.IsValid property is set to True. By using validation controls, you can reduce the messy task of validating HTML form data to a few lines of code.

Controlling Validation Messages

If you have followed the sample program, you have seen that validation controls can be located right next to the fields they are validating. This user interface style is typical of a Web application. However, where screen space is limited you may want to use a ValidationSummary control. A ValidationSummary control is not associated with a particular input field, but instead consolidates the error messages from any other validation controls present on the page having an IsValid property value of False.

Because the validation summary text is built automatically from other validation controls, you still need to set their ErrorMessage properties. However, you can add your own custom header to the validation summary by setting the HeaderText property, as in the following example

 valSum.HeaderText = "Your request cannot be processed because:"  valSum.DisplayMode = ValidationSummaryDisplayMode.BulletList 

Notice in the second line of code we set the DisplayMode property, which determines the format of the validation summary text. In addition to displaying the lists on the Web page, the ValidationSummary control can also generate a message box for browsers that support client scripting. Figure 19.8 shows a message box generated on the client side with the ValidationSummary control.

Figure 19.8. Many of the ASP.NET Server controls will generate client script if the browser supports it.

graphics/19fig08.gif

To use a message box, set the ShowMessageBox property to True. To hide the summary text inside the browser, set the ShowSummary property to False.

Validating Expressions and Other Values

Most of the validation controls included in the ASP.NET framework perform simple validation tests. However, the programming model does accommodate more complex tests by providing a regular expression validation, as well as the ability to program your own validation function.

Using Regular Expressions

You can validate that text in a text box matches complex string patterns using the RegularExpressionValidator control. Regular expressions are special characters that can be used to describe string patterns. For example, in our sample form, we have a field for the user to enter an e-mail address. E-mail addresses typically contain a mailbox name, followed by an at symbol (@), followed by the Internet domain name. If you are following along with the example, add a RegularExpressionValidator control to our sample Web form. Set its ControltoValidate property to txtEmail. Then, all you need to do is specify the appropriate regular expression for a valid e-mail address. Fortunately, Visual Studio already knows it. The Regular Expression Editor, shown in Figure 19.9, includes a lot of predefined expressions for addresses, phone numbers, and other common string fields.

Figure 19.9. Regular expressions are a powerful tool for searching and validating text data.

graphics/19fig09.gif

To display the Regular Expression Editor dialog box, click the ValidationExpression property in the Properties window. For the sample project, select Internet Email Address from the list and click OK. Finally, set the ErrorMessage property to Invalid e-mail address. Now, run the sample program. If you enter invalid e-mail addresses, you should see the error message displayed.

Creating Your Own Validation Function

If none of the other validation controls meet your validation requirements, you may want to use a CustomValidator control. The CustomValidator control automatically calls your custom validation function when necessary, which in turn sets the value for the IsValid property. The validation function can perform whatever tasks you need, such as a database lookup. Listing 19.3 shows a custom subroutine to check whether a date entered in a text box is a weekday.

Listing 19.3 WEBCONTROLS.ZIP Executing a Custom Validation Function
 Private Sub CheckWeekDay(ByVal source As Object, _              ByVal args As ServerValidateEventArgs)      Dim UserInput As String = args.Value      If IsDate(UserInput) Then          Dim TheDate As Date = Convert.ToDateTime(UserInput)          If TheDate.DayOfWeek = DayOfWeek.Saturday _          Or TheDate.DayOfWeek = DayOfWeek.Sunday Then              args.IsValid = False          Else              args.IsValid = True          End If      Else          args.IsValid = False      End If  End Sub 

As you can see from Listing 19.3, the second parameter passed to a custom validation function contains two important properties. The first is the Value property, which contains the value to be validated. The second is the IsValid property, which your custom code can set depending on whether the value is valid. To make the function work, you have to add an event handler for the server-side event:

 AddHandler valMeetingDate.ServerValidate, AddressOf CheckWeekDay 

Note

You can also program a custom JavaScript validation function, which the ValidatorControl will execute on the client. For more details, see the help topic "CustomValidator class."



    Team-Fly    
    Top
     



    Special Edition Using Visual Basic. NET
    Special Edition Using Visual Basic.NET
    ISBN: 078972572X
    EAN: 2147483647
    Year: 2001
    Pages: 198

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