Determining if a string is not null/blank and is a number and not 0? - coldfusion

I normally don't work in ColdFusion but there's a FTP process at work I have to create a report for with the only option right now being a ColdFusion 8 server. This FTP feed has a few issues (trash too).
So, I make the query and then I need to convert some of the string values during the output to do some math. Before that:
How do I tell if a field in the output loop: is not blank or null, is string that can be converted into a valid number, and is not 0?
Is there a simple way of doing this w/o a lot of if statements?
Thanks!

So you want to make sure that the variable is numeric but not zero?
Then you want this:
<cfif IsNumeric(MyVar) AND MyVar NEQ 0 >

Determining if a string is not null/blank and is a number and not 0?
Here's the code I would use in this case.
<cfif isDefined(stringVar) and len((trim(stringVar))) and isNumeric(stringVar)>
do stuff here
</cfif>
isDefined returns a true if the variable exists. If you know the scope of the variable, i.e., its in the form or url scope for instance, you can use structkeyExists(form,"stringVar"). I would recommend using this approach if you know the scope of the variable.
Len(trim(stringVar)) is the second check. First off it trims any leading or trailing empty spaces from the string - this makes sure that any empty variables are not passed along. Then if something is there it will return the length of the string. If its empty len will return a 0.
isNumeric(stringVar) returns a true if the variable is a number and false otherwise.

<cfif Len(field) and Val(field)>
Len() will verify the field has length (not blank--there are no NULLs in CF) and Val() will automatically convert the first character in the string into into a number--or return 0 if it cannot.
Take note of Peter's comment below; although this is the least verbose answer, Val() may fail in certain edge conditions below, ie. The field is a string but starts with a number, incorrectly converting it to a number, and evaluating to TRUE.

<cfif isNumeric(myfield) and myfield gt 0>

Related

How to find a substring anywhere in a string

This should be easy, but I'm finding it difficult.
I just want to find whether a substring exists anywhere in a string. In my case, whether the name of a website exists in the title of a product.
My code is like this:
#FindNoCase("Amazon.com", "Google Chromecast available at Amazon")#
The above returns a 0 which is correct because the entire substring "Amazon.com" doesn't exist in the main string. But some of it does, namely the "Amazon" part.
How could I achieve what I'm trying to do which is just see if ANY of the substring (at least more than 2 character in length) exists in the main string?
So I need something like FindOneOf() but actually "find at least three of". It should then look at the word "Amazon" in the product title and check if at least 3 characters in the sequence of "Amazon.com" exists. When it sees that "Ama" exists, then it just needs to return a true value. Can it be done using the existing built-in functions somehow?
Update: Very simple solution. I used Left("amazon", 3).
There's a lot of danger in false positives, like if someone was buying the Alabama state flag.
Because of store names that contain spaces, this is a little tricky (Wal Mart is often written with a space).
If your string always contains at [store], you can extract the store name by finding the last at in the sentence and creating a string by chopping off everything else.
Because it looks for occurrences of at only as a whole word, there's no danger with store names such as Beats Audio, or Sam's Meat Shop. I can't think of any any stores with the word at in the name. While that would technically trip it up, there's much lower risk, and you can do a pre-replace on such store names.
<cfset mystring = "Google Chromecast available at Amazon">
<cfset SellerName = REReplaceNoCase(mystring,".*\b(?:at)\b(?!.*\b(?:at)\b)\s*","")>
<cfoutput>Seller: #Sellername#</cfoutput>
You can then do your comparisons much more safely.
Per your comment, If you know all possible patterns, you can still obtain the data if you want to (false positives can either be embarrassing or catastrophic, depending on the action). If you know the stores you're working with, you can use a regex to pull out the string like this
<cfset mystring = "Google Chromecast available at Amazon.co.uk">
<cfset SellerName = REReplaceNoCase(mystring,".*\b((Google|Amazon|Wal[\W]*Mart|E[\W]*bay)(\.[a-z]+)*)\b","\1")>
<cfoutput>Seller: #Sellername#</cfoutput>
The only part you need to update is the pipe-delimited list You might add K-Mart as K[\W]*Mart the [\W]* permits any special character or space so it covers kMart, K-Mart, k*Mart, but not Kwik-E-Mart.
Update #2, per more comments
<cfset mystring = "Google Chromecast available at Toys-R-US">
<cfset SellerNameRE = REReplace(rsProduct.sellername,"[\W]+","[\W]*","ALL")>
<cfset TheSellerName = REReplaceNoCase(mystring,".*\b((#sellernameRE#)(\.[a-z]+)*)\b","\1")>
<cfoutput>Seller: #TheSellername# (#SellerNameRE#)</cfoutput>
This replaces any symbols with the wildcard character so that symbols aren't required so that if something says Wal*Mart, it will still match WalMart.
You could also load a seperate column with "Regex Names" so that you're not doing this each time.
So your table would look something like
SellerID SellerName RegexName
1 Wal-Mart Wal[\W]*Mart
2 Toys-R-US Toys[\W]*R[\W]*US
<cfset mystring = "Google Chromecast available at Toys-R-US">
<cfset TheSellerName = REReplaceNoCase(mystring,".*\b((#rsProduct.RegexName#)(\.[a-z]+)*)\b","\1")>
<cfoutput>Seller: #TheSellername# (#SellerNameRE#)</cfoutput>
Solved it by doing this
#FindNoCase(left("Amazon.com", 3), "Google Chromecast available at Amazon")#
Yes there is potential it won't do what I need in cases where the seller name less than 3 characters long. But I think its rare enough to be ok.

ColdFusion 9: int and type="numeric" nasty bug?

I've just experienced a behaviour that defies any logic and could potentially lead to serious issues and was wondering if it was a bug or if the behaviour was itended and what are the best practices to circumvent the issue? If it's a bug, is there a patch?
Here's the two wierd behaviours that when put together are a threat to any system's data integrity.
int('1 2') -> 41276
isValid('numeric', '1 2') -> true
Why? Well let's see...
<cffunction name="deleteSomething" access="public" returntype="void">
<cfargument name="somethingId" type="numeric" required="yes">
<cfquery datasource="#dsn()#">
DELETE
FROM Something
WHERE id = <cfqueryparam cfsqltype="cf_sql_integer" value="#arguments.somethingId#">;
</cfquery>
</cffunction>
<cfset deleteSomething('1 2')>
Here, the type="numeric" arguments validation (which perhaps is based on the same algorithm as isValid?) doesn't throw with '1 2'. Even worse, cfqueryparam cfsqltype="cf_sql_integer" seems to be using int to convert the value which will end up being 41276.
In other words, deleteSomething('1 2') will delete the entity with id 41276 instead of throwing an exception since the value 1 2 is obviously not numeric.
Now, the only fix I thought of is to perform additionnal argument validation using isValid('integer', ... or a regular expression, but that's a real pain and besides, I never understood why they haven't implemented type="integer"?
Obviously, I also always made the false assumption that cfqueryparam type="cf_sql_integer" would validate that the value passed is a valid integer.
EDIT:
It seems that even isvalid('integer', ... is also not reliable as we can see in
Why isvalid("integer","1,5") = YES?
EDIT2:
I know that I could add additionnal arguments validation for every expected integer argument in every function, however that would require to fix a huge code base in my case and it's also very error-prone. It also makes the built-in argument validation completely useless in this case.
I would rather prefer a solution where I could create and apply an unofficial patch. Is that a realistic option? If so I would like to be pointed out in the right direction.
EDIT3: It doesn't solves all the problems, but CF11 added support for a strictNumberValidation application level configuration.
"Starting from ColdFusion 11, this function evaluates on a more strict
basis. Setting this value to false makes the isValid function to
behave in the older way. This setting effects cfargument, cfparam and
cfform tags wherever integer & numeric validation is used. Based on
this setting, the validation reflects in those tags as well."
This is a variation on that theme from the other question. See this code (or run it on cflive.net):
<cfscript>
s = "1 2";
i = int(s);
v = isValid("numeric", s);
d = createOdbcDate(s);
writeDump([s,i,v,d]);
</cfscript>
s converts to 41276 when calling int(), and when using it as an input for createOdbcDate(), we get:
January, 02 2013 00:00:00 +0000
So "1 2" is being interpreted as "m d", with an implied year of the current year.
Which is utterly stupid. But there you go.
You can use regular expressions to find out if there are any non numeric characters in a given form field:
reFind( "[^\d-]", "1 2")
That will match any character that is not a number, not a -
If you want to check only positive numbers, you can use
reFind( "[^\d]", "1 2")
If this returns true, you do not have an integer.

trying to validate string as boolean Coldfusion

I'm currently trying to validate if a string is exactly true or false as I'm building a spreadsheet importer using CF10.
My users will either enter in one of the following.
NULL, which will equate to false
TRUE which obviously equates to true
FALSE which again will equate to false.
I'm trying to use the isValid('boolean',variable.data) to validate if the data is in fact a boolean string or not. However after reading quite a few posts I can see that it will validate true if its a positive number and false if it is a negative one etc.
I'm wondering if anyone has an easy fix to getting boolean validation working for strings easily ? Is this more a regular expressions scenario to make it work properly ?
Any help greatly appreciated.
Assuming you mean the literal string "NULL", one option is using list functions. Search a list of allowed values, ie "true,false,null". If the entry is found, it is valid:
<cfif listFindNoCase("true,false,null", theValue)>
this is a valid boolean value
<cfelse>
not found. do something here...
</cfif>
Then a simple string comparison would return false for everything other than the literal string "true":
isTrue = compareNoCase(e, "true") eq 0 ? true : false`
If you need to evaluate whether a string is exactly "true" or "false", then you are not doing a boolean comparison, you are doing a string comparison.
So to that end, you'd be wanting to use compare() or compareNoCase() (depending on how rigid you need to be).
You could just do some logic or am I missing something.
<cfset booleanResult = enteredValue eq 'TRUE' ? true : false />

convert string to variable coldfusion

I'm a bit stumped on this one..
I currently have a string.
Please enter your variable.firstname here
What i would like to do is find the variable.firstname in the string and convert it to be used as #variable.firstname#
Im using CF8, and ive looked at using findNoCase() but the variable.firstname portion can appear anywhere. I am also trying to use this in a Coldfusion Custom Tag as its to simply display the firstname of the user that could be dynamically populated.
I cant use any other functionality to change it IE = variable['firstname] because the variable could be the result of a dynamic variable i pass in and the query for the content will reside within the custom tag.
<cfset yourNewString = replace(yourOldString,'variable.firstname',
'##variable.firstname##', 'all')>
Note the double pound signs.
I cant use any other functionality to change it IE =
variable['firstname] because the variable could be the result of a
dynamic variable i pass in and the query for the content will reside
within the custom tag.
I'm not sure I understand exactly what you're saying here but if you're saying that variables.firstname is coming from another variable and the .firstname is the dynamic part you could still use array notation.
<cfset myName = "Travis">
<cfset yourName = "user125264">
<cfset myCustomVariable = "myName">
<cfoutput>Hi, My name is #variables[myCustomVariable]#. </cfoutput>
<cfset myCustomVariable = "yourName">
<cfoutput>Your name is #variables[MyCustomVariable]#.</cfoutput>
Output: Hi, My name is Travis. Your name is user125264.
If that isn't what you meant, I apologize.
If you're trying to replace variable.firstname with #variables.firstname# and then also get the value of that variable, you'll need to do the replace <cfset yourNewString = replace(yourOldString,'variable.firstname',
'##variables.firstname##', 'all')> and then wrap the resulting string in an evaluate() function (and an inner de() to prevent CF from evaluating everything): <cfset evaluatedString = evaluate(de(yourNewstring))>.
If there are more variables besides variable.firstname that need this kind of translation, you'll need to get into regex with reReplace() to catch them all in one statement. My regex is rusty, so you'll need to Google that bit on your own. ;o)

Why is ListAppend non destructive, while ArrayAppend and StructInsert are both destructive?

I just spent almost an hour trying to figure out an issue with having a list that would always return an empty string. I was using ListAppend just like one uses ArrayAppend or StructInsert, but apparently ListAppend works differently. What, if any, is the reasoning behind having ListAppend work differently from everything else?
<cfset ListAppend(list, item)>
list = ''
<cfset ArrayAppend(array, item)>
array[1] = item
<cfset StructInsert(struct, 'key', item)>
struct.key = item
Possibly because a list is just a big String. Unlike arrays and structures, Strings are immutable, meaning they cannot be changed. To "append" a new value, you need to create an entirely new String. Arrays and structures are mutable. So you can modify them "in place".
Lists in ColdFusion are just Strings and strings in ColdFusion (and Java) are immutable. They cannot be changed. So ListAppend() must return the a new string with the value instead of modifying the existing string.
<cfset newList = listAppend(oldList, "New Value") />