Work-around for Coldfusion's isNumeric() function
Comments: 0 Stars : 0
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:
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:
Example:
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).
" 8 "
"16d"
"128f"
"32e256"
"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>
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).
Back to entries Comment on this entry