Evik James
Evik James

Reputation: 10493

How to disallow non-alphanumeric characters in ColdFusion using a RegEx

I am using ColdFusion 9.0.1.

I am trying to test whether a user has provided a non alphanumeric value. If they have, I want to return false. I'm pretty sure I am close, but I keep getting an error:

Complex object types cannot be converted to simple values.

I've tried multiple ways of making this work, but I can't get it to work.

Specifically, I want to allow only a through z and 0 through 9. No spaces, or special characters.

Can you help me tweak this?

    <cfscript>
        LOCAL.Description = trim(left(ARGUMENTS.Description, 15));
        if (len(LOCAL.Description) lte 4) {
            return false;
        } else if (reMatchNoCase("[^A-Za-z0-9_]", LOCAL.Description) neq "") {
            return false;
        } else {
            return true;
    </cfscript>

W

Upvotes: 2

Views: 3649

Answers (4)

Dave L
Dave L

Reputation: 3515

I'm late to the party but reFindNoCase is the optimal solution in 2021. Here's how I would handle the code in the original question:

// best practice not to have a local var name identical to an argument var
var myValue = trim( left( arguments.description, 15 ) );

// return false if myValue is less than 4 or has special characters
return(
   !len( myValue ) lte 4 && 
   !reFindNoCase( "[^a-z0-9]", myValue )
);

Upvotes: 0

Peruz Carlsen
Peruz Carlsen

Reputation: 582

You can also try the following approach:

<cfscript>
    local.description = trim(local.description);
    return reFind("(?i)^[A-Z0-9_]{5,}$", local.description)?true:false;
</cfscript>

Upvotes: 2

Jura Khrapunov
Jura Khrapunov

Reputation: 1024

reMatchNoCase returns Array which cannot be compared to the string, use ArrayLen() on the result in order to find out if there any matches

There is actually another problem in your code. First line will produce an error if the length of the description is less than 15, which means that the first IF is obsolete since it will always be false.

Upvotes: 4

Leigh
Leigh

Reputation: 28873

reMatchNoCase("[^A-Za-z0-9_]", LOCAL.Description) neq ""

It is because ReMatchNoCase returns an array, not a simple string. Either check the array length, or better yet, use ReFindNoCase instead. It returns the position of the first match, or 0 if it was not found.

Upvotes: 2

Related Questions