To learn more about author Sanjaya Hettihewa, please visit the author's homepage.
Data conversion and validation are important aspects of application development. Poor data validation and conversion strategies often result in applications that behave erratically when they are presented with unanticipated input. Data conversion and validation functions of the VBScript language can be used to develop robust applications that do not fall apart when presented with invalid input. VBScript data conversion and validation functions are used to develop robust Web applications that gracefully handle invalid input. For example, a user may enter a string in place of a number. In such an event, VBScript data conversion and validation functions can be used to examine the data entered by the user, display an error message, and ask the user to enter a number.
Note: Time, string, and mathematical expression conversion functions are not covered in this chapter. See Chapter 18, "Time- and String-Manipulation Functions," and Chapter 19, "Mathematical Functions," to learn how to convert time, string, and mathematical expressions.
VBScript includes a number of functions that can be used to convert data from one subtype of variant to another. VBScript data conversion functions are used as follows. Data conversion functions are especially valuable when interfacing with other applications and ActiveX components. For example, an ActiveX control might require input in the form of a hexadecimal (base 16) number. In such an event, the Hex() function can be used to convert a base 10 numeric expression to base 16.
Both Int()and Fix()convert numeric expressions into integers. The only difference is that Int() converts a negative number with a fraction into a smaller integer, and Fix() converts a negative number with a fraction into a larger integer. The following examples illustrate how Int() and Fix() handle numbers with fractions. The Int() and Fix() functions can be used to perform mathematical calculations such as approximating the area under a curve.
Int(11.75) = 11 Fix(11.75) = 11 Int(12.45) = 12 Fix(12.45) = 12 Int(-17.75) = -18 Fix(-17.75) = -17 Int(-7.25) = -8 Fix(-7.25) = -7
Hex() returns the hexadecimal (base 16) value of a numeric expression. For example, Hex(10) returns A.
Oct() returns the octal value (base 8) of a numeric expression. For example, Oct(10) returns 12.
CBool() returns the Boolean value of an expression passed into the function. For example, CBool (A=B) returns TRUE if both A and B contain the same value.
Cbyte() converts a number passed to the function into a number of type byte and returns it. For example, if Cbyte() is called with the number 123.678, it returns 123.
CDbl() converts an expression passed into the function into a variant of subtype double.
Chr() returns the ASCII character of an ASCII code. For example, Chr(65) returns the character A. The Chr() function is particularly handy for including special ASCII characters that are hard to include in VBScript string expressions.
CInt() converts an expression into a variant of subtype Integer. For example, CInt (1234.567) returns 1235.
CLng() returns a variant of subtype long after the expression passed into the function is converted into long. For example, CLng (12345.67) returns 12346.
CSng() converts a numeric expression passed to the function into a variant of subtype Single. For example, CSng (12.123456) returns 12.12346.
CStr() converts an expression passed to CStr() into a string and returns it. For example, CStr(123.456) returns the value "123.456".
Val() can be used to obtain a number contained in a string. The function scans the string until it encounters a character that is not part of a number. For example, Val(" 1234 567 in a string") returns the number 1234567.
Data validation functions are used to determine what type of data is stored in an object/expression. For example, IsDate() can be used to validate a date entered by the user. IsDate() returns TRUE if an expression can be converted to a valid date and FALSE otherwise. The following data validation functions are available to VBScript application developers.
IsArray() returns TRUE if a variable is an array and FALSE otherwise.
IsDate() returns TRUE if an expression can be converted to a valid date and FALSE otherwise.
IsEmpty() returns TRUE if a variable has been initialized and FALSE otherwise.
IsError() returns TRUE if an expression is an error code and FALSE otherwise.
IsNull() returns TRUE if an expression is NULL and FALSE otherwise.
IsNumeric() returns TRUE if an expression is numeric and FALSE otherwise.
IsObject() returns TRUE if an expression references an OLE automation object and FALSE otherwise.
The type of variable can be determined using the VarType() function. For example, if IntVariable is an Integer variable, VarType(IntVariable) returns 2. The type of variable can be determined by examining the return value of VarType(). Return values are interpreted in Table 17.1.
Value returned | Type of variable |
0 | Empty |
1 | Null |
2 | Integer |
3 | Long integer |
4 | Single-precision, floating-point number |
5 | Double-precision, floating-point number |
6 | Currency |
7 | Date |
8 | String |
9 | OLE automation object |
10 | Error |
11 | Boolean |
12 | Variant |
13 | Non-OLE automation object |
8192 | Array |
You should always perform data validation when you accept input from users. Failure to do so can result in runtime errors that crash your application. Data validation is very easy to perform. A typical data validation algorithm consists of a data-entry control, a data validation condition, and a loop, and functions as illustrated in Figure 17.1.
The application in Listing 17.1 demonstrates the implementation of a simple data
validation application using VBScript. The application continues to function until
the user types the number 5 and selects another area of the Web page, using the mouse
(or presses the Tab key to shift focus from the input box).
Figure 17.1. The data-entry control obtains
data from the user until the control is satisfied.
1: <!-- 2: © 1996 Sanjaya Hettihewa (http://www.NetInnovation.com/) 3: All Rights Reserved. 4: Permission is hereby given to modify and distribute this code 5: as you wish provided that this block of text remains unchanged. 6: !--> 7: 8: <HTML> 9: <HEAD> 10: 11: <SCRIPT LANGUAGE="VBScript"> 12: <!-- 13: 14: Sub ValidateData() 15: If ( IsNumeric (DataEntryForm.Input.Value) ) Then 16: If ( DataEntryForm.Input.Value=5 ) Then 17: Call ThankUser 18: Else 19: MsgBox "Please enter the number five!" & chr(10) & _ 20: "The number you entered (" & DataEntryForm.Input.Value _ 21: & ") is not the number 5." 22: End If 23: Else 24: MsgBox "Please enter the number five!" & chr(10) & _ 25: "Your input (" & DataEntryForm.Input.Value _ 26: & ") is not a valid numeric expression." 27: End If 28: End sub 29: 30: Sub ThankUser 31: document.open 32: document.write "<BODY BGCOLOR=FFFFFF>" 33: document.write "<H1>" 34: document.write "Thank you for entering the number 5!" 35: document.write "</H1>" 36: document.write "<H2>" 37: document.write "<Have a nice day!>" 38: document.write "</H2>" 39: document.close 40: End Sub 41: 42: --> 43: </SCRIPT> 44: 45: <TITLE>Simple Data Validation</TITLE> 46: </HEAD> 47: <BODY BGCOLOR="#F7FFF4"> 48: 49: <FORM NAME="DataEntryForm"> 50: <p>Please enter the number 5 51: <INPUT LANGUAGE="VBScript" 52: TYPE=text ONCHANGE="call ValidateData()" 53: SIZE=20 NAME="Input"></p> 54: </FORM> 55: 56: </BODY> 57: </HTML>
The user interface of the simple data validation application in Listing 17.1 is
shown in Figure 17.2. When a user types an expression and selects another area of
the Web page, using the mouse, the call ValidateData() statement defined in line
52 of Listing 17.1 is executed. The ValidateData() subroutine validates user input
by first checking whether the user's input is a numeric expression.
Figure 17.2. The simple data validation
application.
If the user enters a non-numeric expression, the dialog box in Figure 17.3 is displayed.
Notice how this dialog box displays the user's input.
Figure 17.3. Error message displayed
when a non-numeric expression is entered.
If the user enters a numeric expression that does not equal the number 5, the dialog
box in Figure 17.4 is displayed. Again, notice how the user's input is returned to
the user to point out the mistake.
Figure 17.4. Error message displayed when a numeric expression other than the number 5 is entered.
Tip: When validating data, it is a good idea to echo what the user enters (as shown in Figures 17.3 and 17.4) if the user's input is not valid.
When a user types the number 5, the ThankUser subroutine defined in lines 30-40
is executed. The output of the ThankUser subroutine can be found in Figure 17.5.
Figure 17.5. Output of the ThankUser
subroutine.
HTML forms are generally used to obtain input from users browsing a Web site.
When the HTML form is submitted to the Web server for processing, the HTML form data
is processed by a CGI application. This transaction can be unnecessarily resource
intensive if a form data-entry field contains invalid input. The guest-book application
in Listing 17.2 (see Figure 17.6) demonstrates how VBScript is used to validate data
in an HTML form before the form is submitted to a CGI application for processing.
Figure 17.6. Data-entry fields of the
guest-book application.
Most HTML forms contain the following line of HTML code:
<input type="submit" value="Submit Comments">
The preceding line of code informs the Web browser to establish an HTTP connection and submit the data of the HTML form. Although this works well for submitting data to the server for processing, it does not allow a client-side VBScript application to validate the data before it is transmitted to the Web server for processing. This problem is solved using the following line of HTML code:
<input type="button" name="SubmitData" value="Submit Comments">
Compare this line of code to the line of code before it, and you will notice the only difference between the two statements is how the data is submitted and the additional HTML field name="SubmitData". This additional HTML field assigns the name SubmitData to the button used to submit the HTML form. When the input type is a Submit button, the Web browser transmits the HTML form data to the CGI application defined in the action= tag of the form declaration as soon as the button is pressed. However, when a regular HTML form button (not a Submit button) is used to submit the data, the HTML form data is not automatically submitted to the Web server by the Web browser. Instead, a VBScript subroutine can validate the HTML form data and submit it to a CGI application if the HTML form data is valid using the Submit method of the Form object (see lines 57 and 60 of Listing 17.2).
1: <!-- 2: © 1996 Sanjaya Hettihewa (http://www.NetInnovation.com/) 3: All Rights Reserved. 4: Permission is hereby given to modify and distribute this code as you wish 5: provided that this block of text remains unchanged. 6: !--> 7: 8: <HTML> 9: <HEAD> 10: 11: <SCRIPT LANGUAGE="VBScript"> 12: <!-- 13: 14: Sub SubmitData_OnClick() 15: 16: ` The following VBScript statements verify HTML form data. 17: 18: If (GuestBookForm.FirstName.Value = "") Then 19: MsgBox "Invalid Input Detected." & Chr(10) & _ 20: "Required data entry field not filled in." & Chr(10) & _ 21: "Please fill in the First Name data entry field and " & _ 22: "try again.", 4112, "Invalid Input Detected" 23: Else If (GuestBookForm.LastName.Value = "") Then 24: MsgBox "Invalid Input Detected." & Chr(10) & _ 25: "Required data entry field not filled in." & Chr(10) & _ 26: "Please fill in the Last Name data entry field and " & _ 27: "try again.", 4112, "Invalid Input Detected" 28: Else If (GuestBookForm.EMailAddress.Value = "") Then 29: MsgBox "Invalid Input Detected." & Chr(10) & _ 30: "Required data entry field not filled in." & Chr(10) & _ 31: "Please fill in the E-Mail Address data entry field and " & _ 32: "try again.", 4112, "Invalid Input Detected" 33: Else If (GuestBookForm.Country.Value = "") Then 34: MsgBox "Invalid Input Detected." & Chr(10) & _ 35: "Required data entry field not filled in." & Chr(10) & _ 36: "Please fill in the Country data entry field and " & _ 37: "try again.", 4112, "Invalid Input Detected" 38: Else If (GuestBookForm.City.Value = "") Then 39: MsgBox "Invalid Input Detected." & Chr(10) & _ 40: "Required data entry field not filled in." & Chr(10) & _ 41: "Please fill in the City data entry field and " & _ 42: "try again.", 4112, "Invalid Input Detected" 43: Else If (GuestBookForm.Comments.Value = "") Then 44: MsgBox "Invalid Input Detected." & Chr(10) & _ 45: "Required data entry field not filled in." & Chr(10) & _ 46: "Please fill in the Comments data entry field and " & _ 47: "try again.", 4112, "Invalid Input Detected" 48: Else If (GuestBookForm.Birthdate.Value <> "") Then 49: If (IsDate (GuestBookForm.Birthdate.Value) = FALSE) Then 50: MsgBox "Invalid Input Detected." & Chr(10) & _ 51: "I'm sorry but the birthday you entered is " & Chr(10) & _ 52: "not a valid earth day. Please enter a valid " & Chr(10) & _ 53: "birthday and try again." & Chr(10) & Chr(10) & _ 54: "Ps: Please e-mail Webmaster if you are not from earth." _ 55: , 4112, "Invalid Input Detected" 56: Else 57: GuestBookForm.Submit ` Submit HTML form data to the server. 58: End If 59: Else 60: GuestBookForm.Submit ` Submit HTML form data to the server. 61: End If 62: End If 63: End If 64: End If 65: End If 66: End If 67: End If 68: 69: End sub 70: 71: --> 72: </SCRIPT> 73: 74: <TITLE>Submit Guest Book Entry</TITLE> 75: </HEAD> 76: <BODY BGCOLOR="#F7FFF4"> 77: 78: <CENTER><TABLE BORDER=3 BGCOLOR=FFFFCC> 79: <TR><TD> 80: <FONT SIZE=+2>Thank you for signing the guest book!</FONT> 81: </TD></TR></TABLE></CENTER> 82: 83: <p>Thanks for taking the time to sign the NetInnovation guest 84: book. As soon as you fill in the following form and press the 85: submit button, your guest book entry will be added to the 86: NetInnovation.Com guest book.</p> 87: 88: <P><B>Please note that data entry fields with a white backgound 89: are optional.</B></P> 90: 91: <form name="GuestBookForm" 92: action="http://www.NetInnovation.com/cgi-bin/GuestBookSubmit.IDC" 93: method="POST"> 94: 95: <TABLE BGCOLOR=FFFFCC> 96: <TR> 97: <TD>First Name Please: </TD><TD><INPUT NAME="FirstName" 98: TYPE="TEXT" COLS=50 SIZE="43" ALIGN=left></TD> 99: </TR> 100: <TR> 101: <TD>Last Name Please: </TD><TD><INPUT NAME="LastName" 102: TYPE="TEXT" COLS=50 SIZE="43" ALIGN=left></TD> 103: </TR> 104: <TR> 105: <TD>E-mail Address Please: </TD><TD><INPUT NAME="EMailAddress" 106: TYPE="TEXT" COLS=50 SIZE="43" ALIGN=left></TD> 107: </TR> 108: <TR BGCOLOR=FFFFFF> 109: <TD>Your Birthdate Please: </TD><TD> 110: <INPUT NAME="Birthdate" TYPE="TEXT" COLS=10 SIZE="10" 111: ALIGN=left> (Example: 02/29/1976)</TD></TR> 112: <TR> 113: <TD>Country </TD><TD><INPUT NAME="Country" TYPE="TEXT" 114: COLS=50 SIZE="43" ALIGN=left></TD> 115: </TR> 116: <TR> 117: <TD>City / State / Province </TD><TD> 118: <INPUT NAME="City" TYPE="TEXT" COLS=50 SIZE="43" ALIGN=left></TD> 119: </TR> 120: </TABLE> 121: 122: <TABLE BGCOLOR=FFFFCC> 123: Please type your comments below. (Feel free to use HTML!)<BR> 124: <TEXTAREA NAME="Comments" WRAP=VIRTUAL ROWS=5 COLS=82 125: SIZE="82" ALIGN=left></TEXTAREA><BR> 126: </TABLE> 127: 128: <TABLE BGCOLOR=000000> 129: <input type="button" name="SubmitData" value="Submit Comments"> 130: <input type="reset" value="Clear Form"> 131: </TABLE> 132: 133: </form> 134: 135: <HR> 136: <strong>In case you are curious, after you press the submit button, 137: your guest book entry is inserted to a Microsoft Access 138: database.</strong> 139: 140: <HR> 141: <h5>Copyright © 1995 Sanjaya Hettihewa. 142: All rights reserved.<br> 143: Revised: October 16, 1996.</h5> 144: <p> </p> 145: </body> 146: </html>
The application in Listing 17.2 is composed of a series of If...Then...Else statements
that check user input for invalid data. See Figure 17.7 for the error message displayed
when a user attempts to submit an empty form.
Figure 17.7. Error message received when
attempting to submit an empty form.
The If...Then...Else statements in lines 18-67 of Listing 17.2 check all required
data-entry fields to ensure that they are filled in. Notice how the VBScript application
informs the user when a required data-entry field is not filled in (see Figure 17.8).
Figure 17.8. The required data-entry
field Comments is not filled in.
Lines 48-58 of Listing 17.2 validate the user's birthday. If an invalid birthday
is entered, the VBScript application displays a message to the user, as shown in
Figure 17.9. (2/29/1975 is not a valid birthday because 1975 was not a leap year.)
Figure 17.9. Error message received when
attempting to submit an entry with an invalid date.
When the guest-book form is properly filled in (as shown in Figure 17.10), the VBScript
application submits the form to the Web server using the Submit method of the HTML
form. See Figure 17.11 for the results of the guest-book entry submission.
Note: The guest-book application presented in this section works with the Internet Database Connector. A thorough overview of the Internet Database Connector is beyond the scope of this chapter. Refer to Chapter 12, "Developing ODBC Database Front-Ends," to learn how to develop Internet Database Connector applications.
Figure 17.10. A valid guest-book entry.
Figure 17.11. The VBScript application
submits the valid guest-book entry to the Web server.
VBScript functions can be used to validate user input before it is processed to avoid possible runtime errors. Tips and techniques presented in this chapter can be implemented to validate user input in HTML and ActiveX forms. Use VBScript data conversion and validation functions to develop robust applications that gracefully handle invalid input.
© Copyright, Macmillan Computer Publishing. All rights reserved.