Function for if one field is entered, then they are all required

I wanted to see if there was an easy way to create a function that takes in five fields (name, address, city, state, zip). If any one of the fields is entered, then all the fields are required. However, if they are all blank, then none are required.  Right now I have a series of if-else statements which is quite cumbersome.
manicdiggityAsked:
Who is Participating?
 
_agx_Connect With a Mentor Commented:
I'd recommend returning only true/false so it's a little more flexible.

<cfset success = isValidAddress(name="a",address="b",city="c",state="d",zip="e")>
<cfif NOT success>
      display your text ie all fields must be entered.
</cfif>

<cffunction name="isValidAddress" returntype="boolean">
	<cfargument name="name" type="string" required="false">
	<cfargument name="address" type="string" required="false">
	<cfargument name="city" type="string" required="false">
	<cfargument name="state" type="string" required="false">
	<cfargument name="zip" type="string" required="false">
	
	<cfset var key = "">
	<cfset var nonEmptyValues = 0>
	<cfloop collection="#arguments#" item="key">
		<cfif structKeyExists(arguments, key) and len(trim(arguments[key]))>
			<cfset nonEmptyValues = nonEmptyValues + 1>
		</cfif>
	</cfloop>	

	<cfif nonEmptyValues and nonEmptyValues lt structCount(arguments)>
		<cfreturn false >	
	<cfelse>	
		<cfreturn true>
	</cfif>
</cffunction>

Open in new window

0
 
_agx_Commented:
CF function or javascript?
0
 
_agx_Commented:
... and what should this function do if one of the required fields is missing?
0
 
manicdiggityAuthor Commented:
CF function. If one of the required fields is missing, it can just return text that all fields must be entered. Thanks!
0
 
manicdiggityAuthor Commented:
Thanks, that worked!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.