Reputation: 1744
I currently have a coldfusion regex that checks whether a string is alphanumeric or not. I would like to open that up a bit more to allow period and underscore characters. How would I modify this to allow that?
<cfset isValid= true/>
<cfif REFind("[^[:alnum:]]", arguments.stringToCheck, 1) GT 0>
<cfset isValid= false />
</cfif>
Thanks
Upvotes: 4
Views: 2785
Reputation: 112220
No need for cfif - here's a nice concise way of doing it:
<cfset isValidString = NOT refind( '[^\w.]' , Arguments.StringToCheck )/>
Alternatively, you can do it this way:
<cfset isValidString = refind( '^[\w.]*$' , Arguments.StringToCheck ) />
(To prevent empty string, change *
to +
)
This method can make it easier to apply other constraints (e.g. must start with a letter, etc), and is a slightly more straight-forward way of expressing the original check anyway.
Note that the ^
here is an anchor meaning "start of line/string" (with $
being the corresponding end), more information here.
Upvotes: 4
Reputation: 9615
This should do it.
<cfset isValidString= true/>
<cfif REFind("[^[:alnum:]_\.]", arguments.stringToCheck, 1) GT 0>
<cfset isValidString= false />
</cfif>
Also using "isValid" for a variable name is not a great practice. It is the name of a function in ColdFusion and could cause you issues someday.
Upvotes: 3