« Validating multiple emails in one field | Main | JavaScript for centering a popup window to the screen »

Validating multiple emails in one field-- server-side

My previous post addressed how to use a client-side script to validate a To:, Cc:, or Bcc: field that may have more than one email address. Since not all people have JavaScript enabled, it's always a good idea to validate on the server as well-- and with multiple emails, you can't just use the function IsValid('email', [field value]) to validate. So, I converted my JavaScript function to ColdFusion code.

It's the same basic idea as the JavaScript: just loop through the field treating it as a list separated by semi-colons, then check each part of the field for 1) a valid email address; 2) whether any brackets are closed; 3) whether brackets are present when needed; and 4) whether any quotes are closed; and 5) whether quotes are present when needed.

Here's the final code:

<cffunction name="AreValidEmails">
	<cfargument name="emailString" type="string" required="Yes" />
	<cfset filter1  = '([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+>?$' />
	<cfset filter2  = '<([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+>$' />
	<cfset filter3  = '"[^"]+"\s?<([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+>$' />
	<cfset result = 1>

	<!--- For each of the parts of the string --->
	<cfloop index="part" list="#ARGUMENTS.emailString#" delimiters=";">
		<!--- Trim spaces from the ends --->
		<cfset part = Trim(part) />
		<cfif part neq '' and not ReFindNoCase(filter1, part)><!--- Check whether an email is present --->
			<cfset result = 0 />
		<cfelseif ReFindNoCase(filter1, part) and ReFind('[<>]', part) and not ReFindNoCase(filter2, part)><!--- Check whether brackets are closed --->
			<cfset result = 0 />
		<cfelseif ReFindNoCase(filter1, part) and Find(' ', part) and not ReFindNoCase(filter2, part)><!--- Check whether brackets are present when needed --->
			<cfset result = 0 />
		<cfelseif ReFindNoCase(filter1, part) and ReFind('["]', part) and not ReFindNoCase(filter3, part)><!--- Check whether quotes are closed --->
			<cfset result = 0 />
		<cfelseif ReFindNoCase(filter1, part) and Find(',', part) and not ReFindNoCase(filter3, part)><!--- Check whether quotes are present when needed --->
			<cfset result = 0 />
		</cfif>
	</cfloop>
	
	<cfreturn result>
</cffunction>

Post a comment


Type the characters you see in the picture above.