Reputation: 163
I'm passing a structure to a function for req. fields validation but I first check whether or not my structure is empty.
If all elements in my structure is empty (emptry string), I don't pass this structure to for validation.
I used StructIsEmpty
to check my structure. The problem is, when my Structure's elements contain only empty string, StructIsEmpty
return NO
. Unfortunately I'm still on CF8.
How can I have StructIsEmpty
to return YES
when all of the structure elements only has empty string?
<cfset st_MyStruct=StructNew()>
<cfset st_MyStruct["InstType"]="#Trim(arr[112])#">
<cfset st_MyStruct["InstId"]="#Trim(arr[113])#">
<cfset st_MyStruct["PLN"]="#Trim(arr[115])#">
<cfset st_MyStruct["PFN"]="#Trim(arr[116])#">
<cfset st_MyStruct["Referal"]="#Trim(arr[118])#">
cfif StructIsEmpty(st_MyStruct) NEQ "NO">
<CFINVOKE component="cfcomponents.ValidateFields" method="CheckReqFields"
st_MyStruct="#st_MyStruct#"
Inst="#arguments.Inst#" >
</cfif>
Upvotes: 0
Views: 2531
Reputation: 14333
Like Dan said, this struct is not empty. If you want to check if your struct has values that are blank you can do something like this. And check if your structFieldsAreEmpty
variables true, if it does then your structure has all blank values. If your struct returns more than one entry you would need to modify this code
<cfset st_MyStruct = {}>
<cfset st_MyStruct["InstType"] = ''>
<cfset st_MyStruct["InstId"] = ''>
<cfset st_MyStruct["PLN"] = ''>
<cfset st_MyStruct["PFN"] = ''>
<cfset st_MyStruct["Referal"] = ''>
<cfset structFieldsAreEmpty = checkStructValuesEmpty(st_MyStruct) />
<cffunction name="checkStructValuesEmpty" access="private" returntype="boolean" output="false">
<cfargument name="myStruct" type="struct" required="true">
<cfloop collection="#arguments.myStruct#" index="i">
<cfif len(trim(arguments.myStruct[i]))>
<cfreturn false>
</cfif>
</cfloop>
<cfreturn true>
</cffunction>
Upvotes: 1
Reputation: 1951
If you want to do this in a single line, you could serialize the struct to JSON and search that using regex for any non-empty string values, like so:
structIsEmptyStrings = refind(':("[^"]+"|\d+|true|false)', serializeJSON(st_MyStruct)) == 0;
That regex is looking for any values that are either not empty strings (""
), numeric, or a boolean value (true
or false
). Keep in mind that this will not be accurate if any values in the struct are any types other than string, numeric, or boolean (nested arrays or structs will not be checked). Also, if any string values are only spaces, this will consider the struct to be not empty (which might not be what you're looking for).
Upvotes: 0