views:

51

answers:

2

Why does the following code not output "Error" if the form is submitted with a blank field? Does Len only evaluate numerical values?

<cfif NOT Len(Trim("Form.myField"))>
 <cfoutput>Error</cfoutput>
</cfif>

The following also does not evaluate as expected:

<cfif Len(Trim("Form.myField")) IS 0>
 <cfoutput>Error</cfoutput>
</cfif>

HTML:

<input type="text" name="myField" value="">
+1  A: 

are you sure you're supposed to pass in the parameter in quotes within the trim function? it may be literally trimming the string "Form.myField"

Jason M
+5  A: 

Because it's evaluating the literal string "Form.myField", which is not length 0.

Try: <cfif len(trim(form.myField)) EQ 0>

Al Everett
Duhhh... thanks! I can't believe it. And I thought my attention to detail was very good. What a stupid mistake to make!
Mel
isDefined() being slightly different and requiring the quotes messed me up when using other functions. I finally got used to it (and pretty much stopped using isDefined()). So, you're not alone.
Al Everett
You would not believe it, Al: Right after I went back to my code (I'm using isDefined) and removed the quotes from that too, and my code stopped working again. I came back here to ask again and saw your additional comment. Now things are good. But how can you stop using isDefined? In my case, I'm using to see if something is not defined, and then if it's length is 0 to output an error; and cfelse to process a query. What would be your alternative?
Mel
structkeyexists()
Jason
As Jason suggests, I have been able to replace virtually all of my isDefined("") with structKeyExists(). I now only use isDefined() if it's absolutely necessary.
Al Everett
Al and Jason, is there a functional reason why you use structKeyExists()? Is it faster? Is it better? Or just to avoid having to use quote marks on scope variables?
Mel
I use it because it's more precise. Because it is more focused it may be faster depending on your JVM. Some other people's thoughts: http://corfield.org/blog/index.cfm/do/blog.entry/entry/isDefined_vs_structKeyExists http://www.simonwhatley.co.uk/isdefined-vs-structkeyexists
Al Everett
Al, according to the following blog IsDefined appears to be faster based on a test by the blog author: http://www.placona.co.uk/blog/post.cfm/performance-test-isdefined-x-structkeyexists What are your thoughts on the test and the result?
Mel
I was able to reproduce the same results. However, in order to see any significant difference, one must loop over the code over 100K times. Even then, you're talking about a difference of a couple dozen milliseconds, and even then it wasn't consistent and structKeyExists won a couple of times. It's not a real-world test. In any case the difference is not nearly enough to override the other benefits. (This has gone far afield the original question. If you want to discuss the merits of isDefined vs. structKeyExists you should create another question.)
Al Everett