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.
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.

<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 nonEmptyValues and nonEmptyValues lt structCount(arguments)>
		<cfreturn false >	
		<cfreturn true>

Open in new window

CF function or javascript?
... and what should this function do if one of the required fields is missing?
manicdiggityAuthor Commented:
CF function. If one of the required fields is missing, it can just return text that all fields must be entered. Thanks!
manicdiggityAuthor Commented:
Thanks, that worked!
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.