vbscript functions

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 characters—wrong 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

Upload: haibye424

Post on 14-Dec-2015

10 views

Category:

Documents


4 download

DESCRIPTION

vbscript

TRANSCRIPT

Page 1: VBscript Functions

INT213 – Lab 5 – Functions

VBScript Built-in FunctionsSee Textbook Day 5. See W3Schools http://www.w3schools.com/vbscript/vbscript_ref_functions.asp#string

String FunctionsVBScript 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 characters—wrong 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 spacestext will now contain "aBcDe"

text = Lcase(text) ' ensure all lower casetext will now contain "abcde"

text = Ucase(text) ' ensure all UPPER casetext 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

Page 2: VBscript Functions

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 THENtextMsg = "Please input ... "

ELSEIF Len(text) = 1 THENtextMsg = "Text is incomplete ... "

END IF ' length of text variable

LAB5a.aspTry 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 spacestext = 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

Page 3: VBscript Functions

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 rangecur - 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 floating-point. 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

Page 4: VBscript Functions

INT213 – Lab 5 – Functions

Therefore, always convert your numeric variables to a true numeric type after testing if it IsNumeric.' validate percentage inputisInputValid = TRUE

IF Len(percentage) = 0 THENpercentageMsg = "Please input a percentage"isInputValid = FALSE

ELSEIF IsNumeric(percentage) = False THENpercentageMsg = "Please input a numeric value"isInputValid = FALSE

ELSE ' numeric value enteredpercentage = Ccur(percentage) ' convert to numeric data type' range check for percentage value: 0-100IF percentage < 0 OR percentage > 100 then

percentageMsg = "Percentage must be between 0 - 100" isInputValid = False

End if ' percent range checkEnd 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 numbersIF Len(name) = 0 THEN

nameMsg = "Please input a name"isInputValid = FALSE

ELSEIF Len(name) = 1 THENnameMsg = "name requires more than one character"isInputValid = FALSE

ELSEIF IsNumeric(name) thennameMsg = "name cannot be a numeric value"

isInputValid = False

End If ' name validations

4 of 13

Page 5: VBscript Functions

INT213 – Lab 5 – Functions

Math FunctionsRound( number, dec ) returns a decimal value rounded to a specific number of decimal positions. e.g.number = 1.2356789number = Round(number, 2) ' will contain 1.24number = 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 FunctionsFormatNumber(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 = -1234567formatNumber( number, 2 ) returns "-1,234,567.00"

number = 1234.567formatNumber( number, 2 ) returns "1,234.57"

Lab 5a continuedUse 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 continuedRecall this from Lab 3:

5 of 13

Page 6: VBscript Functions

INT213 – Lab 5 – Functions

Gotchas when Comparing Strings and NumbersIf 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 gradesIF dGrades = "" THEN

isInputValid = FalsedGradesMsg = "Please input number of D grades"

ELSEIF isNumeric(dGrades)=False THENisInputValid = FalsedGradesMsg = "number of D grades must be numeric"

ELSE ' number of D grades has been input and is numericdGrades = Ccur(dGrades) ' convert to a numeric data typeIF dGrades < 0 THEN

isInputValid = FalsedGradesMsg = "number of D grades must be greater than zero"

ELSEIF dGrades > courses THEN ' check upper rangeisInputValid = FalsedGradesMsg = "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

Page 7: VBscript Functions

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 courseSELECT 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 validationisInputValid = False

CASE ELSE ' ERROR TRAP: unrecognized codediplomaCodeMsg = "Diploma Code must be CPD,CPA,CNS,CTY"course = 999999999 ' value avoids false neg. on D grades validationisInputValid = False

END SELECT ' CASE diplomaCode

More String FunctionsSearching a String

7 of 13

Page 8: VBscript Functions

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 1st

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 unsuccessfulResponse.Write searchText & " not found in text "

ELSE ' character was foundResponse.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 foundResponse.Write "Next " & searchText & " found in position "

& position

8 of 13

Page 9: VBscript Functions

INT213 – Lab 5 – Functions

ELSEResponse.Write "Only one " & searchText & " was found."

END IF ' searchText is found againEND IF ' search for character 'o' in text

There is also an InStrRev function which searches in reverse order—from 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 unsuccessfulResponse.Write searchText & " not found in text "

ELSE ' character was foundResponse.Write searchText & " found in position " & position

' check for another searchTextIF position <> InStrRev(text, searchText) THEN

Response.Write "The last " & searchText & " was found at " & lastPosition

ELSEResponse.Write "Only one " & searchText & " was found."

END IF ' searchText is found againEND IF ' search for character 'o' in text

Lab 5a continued continued continuedAdd 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

Page 10: VBscript Functions

INT213 – Lab 5 – Functions

Extract a partial string from the MIDdle of another stringMID() 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, " ") ' get position of last space = 7

' returns “World” in the most complicated way.lastWord = RIGHT(text, Len(text) - position) ' 12 – 7 = 5lastWord = MID(text, position + 1) ' this is easier than RIGHT()

Replacing TextLike 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

Page 11: VBscript Functions

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.aspUse 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

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

Family Name: GATES IIIGiven Name: WILLIAM H

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

Name validationVerify 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

Click to SUBMIT the above data

Page 12: VBscript Functions

INT213 – Lab 5 – Functions

If only one comma was found, continue the validation inside an ELSEIF ____ 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.

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

Final Lab ResultYou 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.aspFull Name input Expected result[empty] a comma is required to separate family and given

names[ spaces ],, use a single comma to separate the names

12 of 13

Page 13: VBscript Functions

INT213 – Lab 5 – Functions

, [a comma within spaces] Family name not enteredGiven name not entered

a , Family name must be more than one characterGiven name not entered

a , c Family name must be more than one character aa , 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 dd use a single space to separate Family namesuse a single space to separate Given names

aa bb , cc dd accepted. Family: AA BB Given: CC DD aa , c minimum size accepted. Family: AA Given: C

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

Lab Monitor Initials: _________ Date: __________________

13 of 13