Вы находитесь на странице: 1из 13

INT213 Lab 5 Functions

VBScript Built-in Functions


See Textbook Day 5.
See W3Schools
http://www.w3schools.com/vbscript/vbscript_ref_functions.asp#string

String Functions
VBScript has several String functions for handling data that come from
outside your script. In our case, that data comes from a web page. In other
courses, the data may come from command line parameters.
Input from a user comes to your VBScript via an HTML form. Users being
people, they often do not input clean data: the input can have leading
and/or trailing blanks, it could be in mixed case. The user knows what they
mean. To your program, it's just a bunch of characterswrong characters
that will mess up your database inquiries and updates.
Imagine some not-so-good input in a variable:
text = "

aBcDe

"

VBScript has String functions you should always use before dealing with user
input:
Trim(string) returns a string with leading and trailing spaces removed.
Lcase(string) returns all characters in lower case
or Ucase(string) returns all characters in UPPER CASE
text = Trim(text) ' trim spaces
text will now contain "aBcDe"
text = Lcase(text) ' ensure all lower case
text will now contain "abcde"
text = Ucase(text) ' ensure all UPPER case
text will now contain "ABCDE"
Now, what if the input was all spaces? They will all be trimmed away.
Check that the user input something by checking the length of a variable's
contents:
Len(variable) returns the number of positions (characters or digits) in a
variable. The most efficient way for VBscript to check if a variable is empty is
to check if its length is zero. (Checking for an empty string "" also works but
1 of 13

INT213 Lab 5 Functions


a bit more slowly.) Length is also useful for checking if a variable has a
minimum number of characters: is an address or a family name with a single
character valid?
' IF text = "" THEN can be written as...
IF Len(text) = 0 THEN
textMsg = "Please input ... "
ELSEIF Len(text) = 1 THEN
textMsg = "Text is incomplete ... "
END IF ' length of text variable

LAB5a.asp
Try all this out using Lab 3. Copy Lab 3 to Lab5a.asp. Use the above
functions to standardize the user's input of the Diploma Code.
The practice is to
1) retrieve the value from the HTML form into a variable,
2) replace the variable with the trimmed and same case value,
3) return the standardized input back to the HTML INPUT field.
Using the above examples, the code would be:
text = Request.Form("text") ' retrieve input from an HTML field called "text"
text = Trim(text) ' replace without leading/trailing spaces
text = Ucase(text) ' replace with UPPER CASE characters
Hard core programmers might code it this way:
text = Ucase(Trim(Request.Form("text")))
-------------------==========================
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Nested functions are resolved from the inside out. Request.Form("text")
returns a string to the Trim function. Trim returns a string to the Ucase
function. Ucase returns a string which is assigned to the text variable.

Numeric Functions
Check for numeric input and Convert it
Forms return only string data types to your script. If the user is supposed to
input a number, use the built-in function IsNumeric() to test if a string
could be evaluated as a number. Then you can safely convert that variable
into a real number using Ccur() for rounded currency (4 accurate decimals),
2 of 13

INT213 Lab 5 Functions


Clng() to make it a rounded integer (whole number), Cint() to make it a
rounded small integer, INT() to make it a long integer with truncated
decimals, or Cdbl() to make it a double (floating point number). There are
size and accuracy limits due to binary storage. See the following chart.
numeric type contains
range
cur Currency

currency, accurate to 4
decimals
USE THIS TYPE

-922,337,203,685,477.5808 to
922,337,203,685,477.5807

dbl - Double

double-precision floatingpoint.
These decimal position
are approximate!
Do not use for money!
Sadly, this is usually the
default numeric type
used by VBscript.

very, very large numbers in


scientific notation.
Significant digits are accurate
only up to about 15 positions.
Beyond that, floating-point
approximations introduce errors.

lng - Long

big integer

-2,147,483,648 to 2,147,483,647

int - Integer integer

-32,768 to 32,767

Note that the IsNumeric() function does not actually determine whether an
expression contains only numeric digits; it checks if the expression could be
evaluated as a number by the Cxxx conversion functions. Numeric
punctuation such as $,.- is allowed as are leading/trailing spaces.
The conversion functions ignore leading and trailing spaces and consider a
variable without a value to be zero. An empty string or only spaces, such as
might be submitted from a web page, is not numeric and will result in an
error when converted.
percentage = "
-13.0
"
IsNumeric(percentage) ' returns TRUE
But percentage is still a string.

3 of 13

INT213 Lab 5 Functions


Therefore, always convert your numeric variables to a true numeric type
after testing if it IsNumeric.
' validate percentage input
isInputValid = TRUE
IF Len(percentage) = 0 THEN
percentageMsg = "Please input a percentage"
isInputValid = FALSE
ELSEIF IsNumeric(percentage) = False THEN
percentageMsg = "Please input a numeric value"
isInputValid = FALSE
ELSE ' numeric value entered
percentage = Ccur(percentage) ' convert to numeric data type
' range check for percentage value: 0-100
IF percentage < 0 OR percentage > 100 then
percentageMsg = "Percentage must be between 0 - 100"
isInputValid = False
End if ' percent range check
End If ' percentage validations
later on in the script...
' if percentage is valid, process...
IF isInputValid THEN
hst = subTotal * percentage * .01
END IF

IsNumeric() can also be used to check if a variable contains numbers when


it should not:
' validate name is entered and not all numbers
IF Len(name) = 0 THEN
nameMsg = "Please input a name"
isInputValid = FALSE
ELSEIF Len(name) = 1 THEN
nameMsg = "name requires more than one character"
isInputValid = FALSE
ELSEIF IsNumeric(name) then
nameMsg = "name cannot be a numeric value"
isInputValid = False
End If ' name validations

4 of 13

INT213 Lab 5 Functions


Math Functions
Round( number, dec ) returns a decimal value rounded to a specific
number of decimal positions. e.g.
number = 1.2356789
number = Round(number, 2) ' will contain 1.24
number = Round(number, 0) ' will contain 1
Note that Round(number) is equivalent to Round(number, 0).
Use Round() when you want to change the value of a variable. Do not round
the input value, only the final value.
hst = Round(hst, 2) ' round tax to nearest penny
Format Functions
FormatNumber(number, dec) is used to format the output of a number.
Use this when you want to retain the original value of a variable and just
change the way it is presented.
FormatNumber returns a string containing a number with thousands
separator, decimal point with the specified number of positions, and perhaps
a negative sign. The decimals are rounded or padded with zeros as
necessary.
number = -1234567
formatNumber( number, 2 ) returns "-1,234,567.00"
number = 1234.567
formatNumber( number, 2 ) returns "1,234.57"

Lab 5a continued
Use the Round() or the FormatNumber() function to output a whole number
when showing the percentage of D grades. e.g. change the output from this:
Computer Programmer Diploma has 21 courses.
Student with 42.8571428571429% D grades is NOT eligible to graduate.
to this:
Computer Programmer Diploma has 21 courses.
Student with 43% D grades is NOT eligible to graduate.

Lab 5a continued continued


Recall this from Lab 3:

5 of 13

INT213 Lab 5 Functions

Gotchas when Comparing Strings and Numbers


If both operands are variables and one is a "string" and one is a number,
the numeric variable always compares as less than the string variable.
When var1 contains "0" and var2 contains 1, var1 > var2 returns True.
Therefore, when comparing two variables, be sure they have the same
data type.
This is why converting a string containing a number to a real numeric type is
a good practice.
Here is a situation where that is required: add an edit to Lab5a to ensure
that the number of D grades input is not greater than the number of
courses for a diploma. If you do not convert the D grades input (a string)
into a number, then comparing it to the number of courses will not work as
expected. The last ELSEIF is the code to insert into your input validation:
' check for valid range of D grades
IF dGrades = "" THEN
isInputValid = False
dGradesMsg = "Please input number of D grades"
ELSEIF isNumeric(dGrades)=False THEN
isInputValid = False
dGradesMsg = "number of D grades must be numeric"
ELSE ' number of D grades has been input and is numeric
dGrades = Ccur(dGrades) ' convert to a numeric data type
IF dGrades < 0 THEN
isInputValid = False
dGradesMsg = "number of D grades must be greater than zero"
ELSEIF dGrades > courses THEN ' check upper range
isInputValid = False
dGradesMsg = "Number of D grades exceeds the " & courses & _
" courses in the " & diplomaDesc & " diploma"
END IF ' dGrades validation
This edit requires
the input of a valid diploma code which has determined
the number of courses for that diploma
the diploma description

6 of 13

INT213 Lab 5 Functions


In order to know the number of courses before checking the upper limit of
dGrades, we might need to move some code in the script. You may have
something like the following to validate the diploma code:
' check for good Diploma code
IF diplomaCode = "" THEN
isInputValid = False
diplomaCodeMsg = "Please input one of the Diploma Codes shown"
ELSEIF diplomaCode <> "CPA" AND diplomaCode <> "CPD" AND _
diplomaCode <> "CNS" AND diplomaCode <> "CTY" THEN
isInputValid = False
diplomaCodeMsg = "Diploma Code must be CPD,CPA,CNS,CTY"
END IF ' diplomaCode validation
Later on, there is likely a SELECT CASE structure which begins like this:
' look up diploma code, find description and number of course
SELECT CASE diplomaCode
CASE "CNS"
diplomaDesc = "Computer Networking & Technical Support"
course = 23
Delete the IF END IF ' diplomaCode validation structure.
Move the SELECT CASE up to where the IF END IF ' diplomaCode
validation structure was. It must precede the D grades validation.
Lastly, the final part of the SELECT CASE structure should look like the
following. Note how the logic of the old IF END IF diplomaCode validation
structure has been accomplished using CASE statements.
CASE ""
' no input
diplomaCodeMsg = "Please input one of the Diploma Codes shown"
course = 999999999 ' value avoids false neg. on D grades validation
isInputValid = False
CASE ELSE ' ERROR TRAP: unrecognized code
diplomaCodeMsg = "Diploma Code must be CPD,CPA,CNS,CTY"
course = 999999999 ' value avoids false neg. on D grades validation
isInputValid = False
END SELECT ' CASE diplomaCode

More String Functions


Searching a String

7 of 13

INT213 Lab 5 Functions


Often we want to look inside a string for a match with another string. This is
similar to the Find command in a browser. The InStr( ) function lets us do
this. InStr means In String
The syntax of this function is: InStr(string_variable, "search")

string_variable is examined from left to right for the "search" string. The
number of the "search" string's beginning position within the
string_variable is returned. If "search" is not found, zero is returned.
text = "Microsoft"
position = InStr(text, "o")
InStr returns 5. Only the first "o" is found examining from left to right.
There is an option telling InStr to begin looking from other than the 1 st
position.
InStr(start_position, string_variable, "search")
The "search" is begun at the start position.
If "search" is not found, zero is returned.
Example: Find the "o" inside "Microsoft"
text = "Microsoft"
position = InStr(6, text, "o")
InStr begins searching at the 6th position within the search string; it returns
7. The SECOND "o" starts at the 7th character.
To find both "o" characters, the above search could be written:
text = "Microsoft"
searchText = "o"
position = InStr(text, searchText)
IF position = 0 THEN ' search unsuccessful
Response.Write searchText & " not found in text "
ELSE
' character was found
Response.Write searchText & " found in position " & position
' check if searchText is found again starting one position
beyond the first
IF InStr(position + 1, text, searchText) > 0 THEN ' 2nd
searchText found
Response.Write "Next " & searchText & " found in position "
& position
8 of 13

INT213 Lab 5 Functions


ELSE
Response.Write "Only one " & searchText & " was found."
END IF ' searchText is found again
END IF ' search for character 'o' in text
There is also an InStrRev function which searches in reverse orderfrom
right to left, i.e. from the last to the first position. Note that it returns the
same position as InStr (relative to the beginning of the string), only the
search direction is different.
text = "Microsoft"
searchText = "o"
position = InStr(text, searchText)
IF position = 0 THEN ' search unsuccessful
Response.Write searchText & " not found in text "
ELSE
' character was found
Response.Write searchText & " found in position " & position
' check for another searchText
IF position <> InStrRev(text, searchText) THEN
Response.Write "The last " & searchText & " was found at "
& lastPosition
ELSE
Response.Write "Only one " & searchText & " was found."
END IF ' searchText is found again
END IF ' search for character 'o' in text

Lab 5a continued continued continued


Add an edit to Lab5a to ensure that the number of D grades input is
not a decimal number: use InStr() to search for a decimal point (period,
".") in the D grades input. The number of D grades can only be a whole
number.
Resist the urge to compare Ccur(dGrades) <> INT(dGrades), i.e. if a
decimal data type is not equal to the truncated integer value, then the
number contains decimal positions. This is true only for values up to 37,767
after that the INT() function will fail causing an ASP error.
Lab5a.asp summary: use the above functions to standardize the user's
input of the Diploma Code. Validate that the number of D grades is numeric
and does not contain a decimal value, convert the value to a numeric data
type and then check the upper limit of the number of D grades. Finally,
round the percentage output to one decimal position.

9 of 13

INT213 Lab 5 Functions

Extract a partial string from the MIDdle of another string


MID() can extract part of a string allowing us to use portions of the data.
The syntax of the MID() function is:
MID(string_variable, From_Start_Position, positions_to_get)
If "positions to get" is not specified, MID returns everything From the Start
Position to the end of the string.
MID( ) Examples:
text = "Hello World"
position = InStr(text, " ")

' get position of first space

' separate text into separate words


firstWord = MID(text, 1, position-1) ' returns Hello
secondWord = MID(text, position+1) ' returns World
Convenience functions similar to MID are RIGHT and LEFT. But just use MID.
LEFT(string_variable, positions_to_get_from_the_start)
This is equivalent to MID(string_variable, 1, positions_to_get)
RIGHT(string_variable, positions_to_get_from_the_end)
This is equivalent to MID(string_variable, starting_position)
RIGHT & LEFT Examples:
text = "Hello, World"
position = InStr(text, " ")

' get position of first space = 7

firstWord = LEFT(text, position-1) ' returns Hello,


position = InStrREV(text, " ")
= 7

' get position of last space

' returns World in the most complicated way.


lastWord = RIGHT(text, Len(text) - position) ' 12 7 = 5
lastWord = MID(text, position + 1) ' this is easier than RIGHT()

Replacing Text
Like the find and replace feature in editors, scripts may need to replace
characters in a string. The Replace() function allows us to do just that. The
syntax of this function is:

10 of 13

INT213 Lab 5 Functions

Replace(string_variable, "search_for", "replace_with")


Replace returns a new string with any "searched for" characters "replaced".
path = "C:/folder/subFolder/file.ext"
MSpath = Replace(path, "/", "\")
MSpath now contains "C:\folder\subFolder\file.ext"

LAB5b.asp
Use the Lab5b_template.asp from the web page for the next task. Lab5b
takes a full name as input, validates, and parses it into Family & Given
names.

input full name, parse into Family & Given names


Full Name in the format:
Family, Given

GATES

WILLIAM H

[add leading/trailing spaces and spaces before/after the comma and within names]
[try input with and without one or two commas]
Click to SUBMIT the above data

Family Name: GATES III


Given Name: WILLIAM H

Input standardization
Retrieve the Full Name from the form, Trim it of leading and trailing spaces,
and convert the data to upper case.

Name validation
Verify that Full Name variable contains "," (a comma). Issue a message if a
comma was not found or another message if a second comma was found.
Use the InStr and InStrRev functions.

11 of 13

INT213 Lab 5 Functions


If only one comma was found, continue the validation inside an ELSE
IF ____ THEN ' no comma found

ELSEIF ____ THEN ' more than one comma found

ELSE ' one and only one comma found


more logic here that depends on finding the position of
a single comma
END IF ' name validation
Use the MID function to separate the Full Name into Family and Given
Names. Use the Trim function to remove any extra spaces between the
name and comma.
Check for duplicate spaces within the family name. Use InStr function to look
for " " (two spaces) within the family name variable. If found, tell the user
single spacing is required to separate multiple family names.
Check the family name contains at least two characters. Use the Len
function.
Check for duplicate spaces within the given name.
Check the given name contains at least one character. Use the Len function.

Processing
If input is valid, format a message to be output to the user reporting the
Family and Given names. See the sample above.

Final Lab Result


You have created an interactive form which standardizes the user's text
input: leading/trailing spaces are removed, case is all upper. The input
contained a single comma to separate the family and given names.
Your script separated the names into variables such that they could be used
reliably to do a database look up.
Test Cases for INT213lab5b.asp
Full Name input
Expected result
[empty]
[ spaces ]

a comma is required to separate family and given


names

,,

use a single comma to separate the names

12 of 13

INT213 Lab 5 Functions

[a comma within spaces]

Family name must be more than one character


Given name not entered

a ,
a ,
aa

Family name not entered


Given name not entered

c
,

Family name must be more than one character


cc

dd

use a single space to separate Given names

aa

bb ,

cd dd

use a single space to separate Family names

aa

bb ,

cc

use a single space to separate Family names


use a single space to separate Given names

aa bb ,
aa

, c

cc dd

dd

accepted. Family: AA BB Given: CC DD


minimum size accepted.

Family: AA Given: C

Student Initials: _________ Student No. (first 6 only) __ __ __ __ __ __


Lab Monitor Initials: _________

Date:

__________________

13 of 13

Вам также может понравиться