Coldfusion 8: IsDefined('URL.variable') and is not ""?

16,352

Solution 1

<cfif structKeyExists(url, 'affiliateID') and trim(url.affiliateID) neq "">...</cfif>

Solution 2

You can simplify the logic a bit as well by using <cfparam> to ensure that the URL variable always exists. Then rather than having 2 conditions, you just need 1.

<cfparam name="URL.affiliateId" type="string" default="" />

<cfif trim( URL.affiliateId ) is not "">
     do stuff here
</cfif>

Solution 3

To ignore most white space

<cfif IsDefined('URL.affiliateId') and len(trim(URL.affiliateId))>
    value is defined and not empty
</cfif>

... or alternately

<cfif IsDefined('URL.affiliateId') and len(trim(URL.affiliateId)) gt 0>
    value is defined and not empty
</cfif>
Share:
16,352
dcolumbus
Author by

dcolumbus

Updated on June 26, 2022

Comments

  • dcolumbus
    dcolumbus over 1 year

    I'm trying to find out if a url variable exists, and if it doesn't, make sure that it's not empty.

    This does not work:

    <cfif IsDefined('URL.affiliateId') and is not "">
        //
    </cfif>
    
  • Stephen Moretti
    Stephen Moretti about 13 years
    As Leigh says: no #'s are requires, plus if you know the scope and variable name you should always use structkeyexists() as shown by scrittler
  • Harrison
    Harrison about 13 years
    yeah I know that #s are required, it's just one of those habits.
  • Leigh
    Leigh about 13 years
    Good point about structKeyExists(). Either works, but it is a bit more precise.
  • Leigh
    Leigh about 13 years
    I think they have a CF support group for that .. ;)
  • Leigh
    Leigh about 13 years
    Ah, much better. (I am always amazed how many ways you can write this kind of thing ;-)
  • Leigh
    Leigh about 13 years
    True. If the variable's existence does not negatively effect existing code (I was not sure), then cfparam can simplify things
  • Leigh
    Leigh about 13 years
    No there are perfectly valid use cases for all of the above. Personal preference, on the other hand, is a different matter.
  • abdev
    abdev about 13 years
    Also it's been proven the sturctKeyExists is more efficient than IsDefined.
  • Uphill_ What '1
    Uphill_ What '1 about 13 years
    Yes, they are valid but not needed.
  • Stephen Moretti
    Stephen Moretti about 13 years
    Just so you know why StructKeyExists is more efficient; StructKeyExists() looks for a single variable in a single structure. isDefined() will scan every scope in a prescribed order until it find the variable, even if you specify the scope for the variable in the function call. eg. isDefined("session.userid") will still scan the variables, URL, Form etc scopes until it finds it in the session scope.
  • Leigh
    Leigh about 13 years
    While there are similarities in behavior, there are also differences. So a blanket statement that they are never needed is inaccurate. They do not all provide identical functionality.