What is the quickest and easiest way (in Classic ASP) to check if a string has some string (that has a length greater than 0) i.e. NOT "Null", "Nothing", "Empty", or '' empty string
To make sure that the Variant you deal with is of sub-type "string", you need the VarType or TypeName function. To rule out zero length strings, you need Len(). To guard against strings of space, you could throw in a Trim().
Code to illustrate/experiment with:
Option Explicit
Function qq(s) : qq = """" & s & """" : End Function
Function toLiteral(x)
Select Case VarType(x)
Case vbEmpty
toLiteral = "<Empty>"
Case vbNull
toLiteral = "<Null>"
Case vbObject
toLiteral = "<" & TypeName(x) & " object>"
Case vbString
toLiteral = qq(x)
Case Else
toLiteral = CStr(x)
End Select
End Function
Function isGoodStr(x)
isGoodStr = False
If vbString = VarType(x) Then
If 0 < Len(x) Then
isGoodStr = True
End If
End If
End Function
Dim x
For Each x In Array("ok", "", " ", 1, 1.1, True, Null, Empty, New RegExp)
WScript.Echo toLiteral(x), CStr(isGoodStr(x))
Next
output:
cscript 26107006.vbs
"ok" True
"" False
" " True
1 False
1.1 False
True False
<Null> False
<Empty> False
<IRegExp2 object> False
Here's a one-liner that dodges all the trouble with Null by concatenating the value with an empty string. It works for Null, Empty, "", and, of course, strings with actual length! The only one it doesn't (nor shouldn't) work for is Nothing, because that's for object variables, of which a string is not.
isNullOrEmpty = (Len("" & myString) = 0)
You could try having something like this:
Function nz(valToCheck, valIfNull)
If IsNull(valToCheck) then
nz = valIfNull
Else
nz = valToCheck
End if
End function
and then you would use it like this:
if nz(var,"") <> "" then
'--string has something in it
else
'--string is null or empty
end is
You can use the VarType() function to check if it is a string, then you can check if the string is not empty. This statement will only pass through a string that isn't empty.
If VarType(MyString) = 8 Then
If MyString <> "" Then
'String is Not Null And Not Empty, code goes here
End If
End If
This worked for me:
if mystring = "" then wscript.echo "Empty string"
else wscript.echo "String is not empty"
<%
Dim x,y
x = "abcdefg"
'counting length of string
y = Len(x)
Response.Write (y)
'checking string is empty or not
If Len(x) = 0 then
Response.Write ("<p>String is empty</p>")
Else
Response.Write ("<p>String is not empty</p>")
End If
%>
Hope this is helpful.
Related
I have a web service which returns a json response as follows:
"database" ; True
"cpu usage" ; 30%
"connection response" ; 1
"memory" ; 48%
The requirement is to create a vb script which would read through the results, compare it against a set threshold and set a flag accordingly.
That is, I need the result to say "green" if the value against "database" is "true", cpu usage is less than 80%, connection response is more than 0 and memory usage is less than 80%.
Could someone please help me with the above request. This is actually to be used with SCOM monitoring.
Your JSON will be more like this. Note that I have changed the variable names to remove spaces - you will need to modify the code accordingly if these guesses were wrong. In JSON variable names and any non-numeric values are in quotes. Typically you would use a JSON parser to handle this but if it really is this simple you can use some simple string handling code to proceed.
{
"database": "true",
"cpu_usage": 30,
"connection_response": 1,
"memory": 48
}
Call this function passing it the JSON string that you get from the service. It works on the basis that a JSON string is a string and we can chop it about to get usable values IF it is of simple format. If it becomes a more complex message then you will need to search for a JSON parser for VB, or if the interface can respond in XML you will find it much easier to handle in VB.
This is VB6 code (easier for me to test with) - you will need to remove all of the 'as string', 'as integer' etc from the variable declares for VB Script. I have included a val() function for VBScript sourced from here though not tested with my function. You need val() as the JSON is string formatted and if you try to compare numeric values to strings you will get unexpected results.
'
' Function to return RED or GREEN depending on values in simple JSON
'
Function checkStatus(sJSON As String) As String
Dim aVals() As String, aParams() As String, i As Integer, sName As String, sVal As String
Dim bDatabase As Boolean, bCPU As Boolean, bConnection As Boolean, bMemory As Boolean
aVals = Split(sJSON, ",")
For i = 0 To UBound(aVals)
aVals(i) = Trim(aVals(i)) ' remove any leading & trailing spaces
aVals(i) = Replace(aVals(i), "{", "") ' remove braces open
aVals(i) = Replace(aVals(i), "}", "") ' remove braces close
aVals(i) = Replace(aVals(i), """", "") ' remove quotes > "database: true"
Debug.Print "vals[" & i & "]=" & aVals(i)
If Len(aVals(i)) > 0 Then ' should catch any dodgy JSON formatting but may need refinement
aParams = Split(aVals(i), ":") ' split the line e.g. "database: true" > "database" and " true"
If UBound(aParams) > 0 Then
sName = LCase(Trim(aParams(0))) ' now we have sName = "database"
sVal = LCase(Trim(aParams(1))) ' and sVal = "true"
Select Case sName
Case "database"
bDatabase = False
If sVal = "true" Then
bDatabase = True
End If
Case "cpu_usage"
bCPU = False
If Val(sVal) > 80 Then
bCPU = True
End If
Case "connection_response"
bConnection = False
If Val(sVal) > 0 Then
bConnection = True
End If
Case "memory"
bMemory = False
If Val(sVal) < 80 Then
bMemory = True
End If
End Select
End If
End If
Next i
checkStatus = "RED" ' default return value to indicate an issue
' compare the flags to decide if all is well.
If bDatabase And bCPU Then 'And bConnection And bMemory Then
checkStatus = "GREEN"
End If
End Function
Function Val( myString )
' Val Function for VBScript (aka ParseInt Function in VBScript).
' By Denis St-Pierre.
' Natively VBScript has no function to extract numbers from a string.
' Based shamelessly on MS' Helpfile example on RegExp object.
' CAVEAT: Returns only the *last* match found
' (or, with objRE.Global = False, only the *first* match)
Dim colMatches, objMatch, objRE, strPattern
' Default if no numbers are found
Val = 0
strPattern = "[-+0-9]+" ' Numbers positive and negative; use
' "ˆ[-+0-9]+" to emulate Rexx' Value()
' function, which returns 0 unless the
' string starts with a number or sign.
Set objRE = New RegExp ' Create regular expression object.
objRE.Pattern = strPattern ' Set pattern.
objRE.IgnoreCase = True ' Set case insensitivity.
objRE.Global = True ' Set global applicability:
' True => return last match only,
' False => return first match only.
Set colMatches = objRE.Execute( myString ) ' Execute search.
For Each objMatch In colMatches ' Iterate Matches collection.
Val = objMatch.Value
Next
Set objRE= Nothing
End Function
I need a function to check if a string is all (or mostly) capitals using classic asp. (I need to prevent users from inputting titles using all capitals.)
For example, if a string of 30 letters contains 20 or more that are capitalized, I'd need to flag it as "All capitals". So "The Count of Monte Cristo" would be fine, but "The COUNT of MONTE CRISTO" would not.
I was thinking about starting with a count of letters that match [^A-Z], but how do I do that?
This needs to be in Classic ASP and not VB.
Comparing against UCase(input) makes it an all or nothing check; I'd prefer to look at the UCase ratio:
Option Explicit
Function Ucasity(s)
If Len(s) Then
Dim r : Set r = New RegExp
r.Global = True
r.Pattern = "[A-Z]"
Dim m : Set m = r.Execute(s)
Ucasity = m.Count / Len(s)
Else
Ucasity = 0
End If
End Function
Function qq(s) : qq = """" & s & """" : End Function
Dim s
For Each s In Array( _
"UPPERCASE but not ALL OR NOTHING" _
, "UPPERCASE" _
, "pipapo" _
, "UPPERCASEuppercase" _
, "" _
)
WScript.Echo qq(s), CStr(s = UCase(s)), UCasity(s)
Next
output:
cscript 39261181.vbs
"UPPERCASE but not ALL OR NOTHING" False 0,65625
"UPPERCASE" True 1
"pipapo" False 0
"UPPERCASEuppercase" False 0,5
"" True 0
Simply use the UCase function
<%
dim a
a = "This is a test 1"
dim b
b = "THIS IS A TEST 2"
If a = ucase(a) then response.write(a & " is all upper")
If b = ucase(b) then response.write(b & " is all upper")
%>
Result
THIS IS A TEST 2 is all upper
I'm new to vb i don't get the difference between these 2 statements:
isEmpty(value)
and
Trim(value) = ""
Can you explain it? Are they equals?
edit:
i have a code like this in my example
if isempty(request.form("alias")) then
...
elseif trim(request.form("alias")) = "" then
...
end if
All VBScript variables are Variants, but there are subtypes. An empty/not initialized variable has the subtype Empty. The value of such a variable 'works' like 0 or "" in expressions:
>> Dim EmptyVar
>> WScript.Echo VarType(EmptyVar), TypeName(EmptyVar), 1 + EmptyVar, "a" & EmptyVar & "c"
>>
0 Empty 1 ac
>> WScript.Echo CStr(EmptyVar = 0), CStr(EmptyVar = "")
>>
True True
A string variable (initialized by a literal or a string expression) has the subtype String.
It may be empty - i.e. contain no characters - but such a beast is not of subtype Empty:
>> Dim NixStr : NixStr = ""
>> WScript.Echo VarType(NixStr), TypeName(NixStr), 1 & NixStr, "a" & NixStr & "c"
>>
8 String 1 ac
>>
The VBScript function IsEmpty() checks whether a variable is empty/not initialized:
>> WScript.Echo CStr(IsEmpty(EmptyVar)), CStr(IsEmpty(NixStr))
>>
True False
That is why you should check the return value of Inputbox() with IsEmpty() - did the user cancel/abort - and against "" - did the user try to feed "" to the program.
Trim returns the string without ony spaces on the left or right. Eg, " hello world " will become "hello w world".
isEmpty returns a boolean. If the string is empty ("") it will return true, otherwise it will return false.
I have to extract the integer value from a string.
Its actually an amount field.
Say string can be 000000000000512 or 0000040000000
I want only the integer value from this string i.e.; 512/ 40000000
Please help with this in VB scripting
CInt("000000000000512")
See conversion functions: http://msdn.microsoft.com/en-us/library/s2dy91zy.aspx
Use Clng if you expect to have large numbers, as already pointed out in a comment:
Clng("000000004000512")
otherwise you'll have an overflow, as variant's subtype int is 16 bit in vbscript
This will work even with a crazy long number
Function RemoveLeadingZeroes(ByVal str)
Dim tempStr
tempStr = str
While Left(tempStr,1) = "0" AND tempStr <> ""
tempStr = Right(tempStr,Len(tempStr)-1)
Wend
RemoveLeadingZeroes = tempStr
End Function
strNewFileName = RemoveLeadingZeroes("0009283479283749823749872392384")
Use the Absolute Value of the number.
http://ss64.com/vb/abs.html
Var = ABS(Var)
I've used this technique before:
replace the zeros with spaces
left trim
replace the spaces with zeros
Replace(LTrim(Replace(str, "0", " ")), " ", "0")
Note, this doesn't work if str has meaningful spaces in it.
Function TrimLeadingZeros(value)
TrimLeadingZeros = value
while left(TrimLeadingZeros, 1) = "0" and TrimLeadingZeros <> "0"
TrimLeadingZeros = mid(TrimLeadingZeros, 2)
wend
End Function
or
Function TrimLeadingZeros(value)
dim i
i = 1
while i < len(value) and mid(value,i,1) = "0"
i = i + 1
wend
TrimLeadingZeros = mid(value, i)
End Function
Using regex:
Regex.Replace("000000000000512", "^0+", "") ' returns "512"
Regex.Replace("0000040000000", "^0+", "") ' returns "40000000"
In case your string includes digits and characters, use a Do While statement:
string = "00000456ABC"
Do While Left(string, 1) = "0"
string = Right(string, (Len(string)-1))
Loop
Function TrimLZ(str)
If Left(str, 1) = "0" Then
TrimLZ = TrimLZ(Mid(str, 2, Len(str)))
Else
TrimLZ = str
End If
End Function
I'm new to vb and trying to figure things out via searching the net or asking colleagues but now I hit a dead end. I want to have my program to make sure that all my textboxes are filled before saving into the db.
Here is my code:
Private Sub CmdSave_Click()
Set rs = New ADODB.Recordset
With rs
.Open "Select * from table1", cn, 2, 3
If LblAdd_Edit.Caption = "ADD" Then
If MsgBox("Do you want to save this new rocord?", vbQuestion + vbYesNo, "FJD Inventory") = vbNo Then: Exit Sub
.AddNew
!Type = TxtName.Text
!System = txtsys.Text
!acc = TxtAcc.Text
!owner = TxtOwn.Text
!dept = TxtDpt.Text
!svctag = txtSvcTag.Text
.Update
Else
If MsgBox("Do you want to save this changes?", vbQuestion + vbYesNo, "FJD Inventory") = vbNo Then: Exit Sub
Do While Not .EOF
If LvList.SelectedItem.Text = !Type Then
!Type = TxtName.Text
!System = txtsys.Text
!acc = TxtAcc.Text
!owner = TxtOwn.Text
!dept = TxtDpt.Text
!svctag = txtSvcTag.Text
.Update
Exit Do
Else
.MoveNext
End If
Loop
End If
End With
Form_Activate
Save_Cancel
End Sub
I was trying to add the following
If TxtName.Text = "" Or txtsys.Text = "" Or TxtAcc.Text = "" Or TxtOwn.Text = "" Or TxtDpt.Text = "" Or txtSvcTag.Text = "" Then
MsgBox("All Fields Required", vbCritical, "Error") = vbOK: Exit Sub
When I run the program I get a compile error
function or call on the left-hand side of assignment must return a variant or object. I use that msgbox function all the time but now its the line I get an error
If TxtName.Text = "" Or txtsys.Text = "" Or TxtAcc.Text = "" Or TxtOwn.Text = "" Or TxtDpt.Text = "" Or txtSvcTag.Text = "" Then
If MsgBox("All Fields Required", vbCritical, "Error") = vbOK Then Exit Sub
Here is a generic solution. It uses a function to check each textbox on the form and demonstrates using the function. I also compare the text length rather than the text to an empty string because (in general) numeric comparisons are faster than string comparisons.
Private Sub Command1_Click()
If ValidateTextFields Then
MsgBox "Your changes have been saved."
Else
MsgBox "All fields are required."
End If
End Sub
Private Function ValidateTextFields() As Boolean
Dim ctrl As Control
Dim result As Boolean
result = True 'set this to false if a textbox fails
For Each ctrl In Me.Controls
If TypeOf ctrl Is TextBox Then
If Len(ctrl.Text) = 0 Then
result = False
Exit For 'bail on the first failure
End If
End If
Next ctrl
ValidateTextFields = result
End Function
In VB6, you can use Trim() function so that spaces not considered as characters.
If (Trim$(txtGOSID.Text) = "") Then
msgBox "Please provide input.", vbExclamation
With the $ sign, Trim() returns a String value directly; without the $
sign, Trim() returns a Variant with a sub-type of String.