Problem: You need to
determine whether a given input is a number or not.
Unfortunately, Coldfusion's isNumeric() function only checks whether a
number can be treated as a number internally. Therefore, the
following strings (without the quotation marks) would cause the
function to return a true value:
" 8 "
"16d"
"128f"
"32e256"
Although this is fine for many applications, this is often not the
desired behaviour such as when you need to validate them before passing
it to a MySQL query.
Solution: A solution I've
found so far is to use Regular Expressions. We use REFind to
search for the following regex pattern:
^-?[0-9]+(\.?[0-9]+)?$
Example:
<cfif REFind("^-?[0-9]+(\.?[0-9]+)?$", "-256.")>
This is a vaild number.
<cfelse>
This is not a valid number.
</cfif>
Please note that this is also applicable to other programming languages
that support Regular Expressions (i.e.: either built-in or through a
library), although this may no longer be necessary for more elegant
languages such as PHP (sorry, I'm biased).
|