jyoseph
jyoseph

Reputation: 5455

Coldfusion - Remove all non-numeric values from a list?

I have a list of IDs being passed through the URL. I want to do some sanitizing before running a query based on those IDs. I have this:

<cfset URL.ID = ReReplaceNoCase(URL.ID,"[^0-9]","","ALL")>

But I realize that's stripping the comma out also. Is there a simple way to remove non numeric values from a list in Coldfusion?

Upvotes: 10

Views: 14825

Answers (4)

Matt Busche
Matt Busche

Reputation: 14333

@orangepips

isNumeric() should work as well.

<cfset url.id = "100,abc,102z,eee,22.5,773">
<cfset variables.newlist = ''>
<cfloop list="#url.id#" index="i">
    <cfif isNumeric(i)>
        <cfset variables.newlist = ListAppend(variables.newlist,i)>
    </cfif>
</cfloop>
<cfoutput>#variables.newlist#</cfoutput>

Upvotes: 0

Bradley Moore
Bradley Moore

Reputation: 748

<cfscript>
//Test Case
URL.ID= "abc,12,3,zoiui fdsoaiu ,323333";

//URL.ID= "12,3,323333"
URL.ID= reReplace( URL.ID , "([^0-9,]+,)" , "" , "all" );

</cfscript>

That being said, you'd want to put this in a <cfqueryparam .. list= "true" />

Upvotes: 4

orangepips
orangepips

Reputation: 9971

Regex still leaves extra commas in the string and accepts partial numbers, instead I'd use a loop with integer validation:

<cfset url.id = "100,abc,102z,eee,22.5,773">
<!--- 100,,102,,225,773 --->
<cfoutput>#ReReplaceNoCase(URL.ID,"[^0-9,]","","ALL")#<br /></cfoutput>

<cfset dirtyIds = listToArray(url.id)>
<cfset cleanIds = []>
<cfloop array="#dirtyIds#" index="dirtyId">
    <cfif isValid("integer",dirtyId)><cfset arrayAppend(cleanIds, dirtyId)></cfif>
</cfloop>
<cfset url.id = arrayToList(cleanIds)>
<!--- 100, 773 --->
<cfoutput>#url.id#</cfoutput>

Upvotes: 3

Sean Coyne
Sean Coyne

Reputation: 3884

Why not just add a comma to your regex?

<cfset URL.ID = ReReplaceNoCase(URL.ID,"[^0-9]","","ALL")>

becomes

<cfset URL.ID = ReReplaceNoCase(URL.ID,"[^0-9,]","","ALL")>

Upvotes: 22

Related Questions