Tuesday, May 5, 2009

Coldfusion List Validator

When working with coldfusion lists from user-entered-data, or from a database of user-entered-data, it's very important to make sure it's a valid data and validly formatted - one comma between each value, only numeric (if desired - as in this case), and no leading or trailing commas.

Coldfusion is abolutely amazing with lists. So much easier than arrays and structures, and with instant conversion to and from an array. Beautiful! But lists can become invalid very easily, especially when working with numeric lists and using those lists in queries.

This is an easy, solid solution to validating numeric lists:

<cfset test = ",22,,345,456,7 8,4x,1,,,">
<cfoutput>#test#</cfoutput><br /><br />
<cfset test = REPLACE(REREPLACE(test,"^,*|,*$|[^\d,]","","ALL"),",,",",","ALL")>
<cfoutput>#test#</cfoutput>

22,345,456,78,4,1

In the case of '..,7 8,..' one might want to replace spaces with commas so that the resulting number in the list '78' is not created.

As a function:

function listval(listin) {
listin = REPLACE(REREPLACE(listin,"^,*|,*$|[^\d,]","","ALL"),",,",",","ALL");
if(ListLen(TRIM(listin)) IS 0  OR  TRIM(listin) IS "") { listin = "0"; }
return listin;
}

Safe.

And that's a wrap.