Regular expressions are a nice way to validate. Have a look at which option you could use here:
<cfif not reFind("^[0-9]+\.[0-9]{2}$", dataValue)>
<cfthrow type="IllegalArgumentException" message="You may input a decimal value with two decimal places only!">
</cfif>
^
= value has to start with the upcoming pattern
[0-9]+
= match digits from 0 to 9, one digit or more
\.
= a dot (literally), the backslash is an escape symbol since .
has a different effect
[0-9]{2}
= match digits from 0 to 9, exactly two digits
$
= value has to end with the previous pattern
If you want to accept dot and comma as decimal separator, you can change \.
to [,.]
.
If you want to accept one or two decimal spaces, you can change [0-9]{2}
to [0-9]{1,2}
.
If you don't require decimal places at all, but when they are present, they have to have two decimal places:
<cfif not reFind("^[0-9]+(\.[0-9]{2})?$", dataValue)>
<cfthrow type="IllegalArgumentException" message="You may input a decimal value without decimal places or with exactly two decimal places only!">
</cfif>
(\.[0-9]{2})?
= the parenthesis group the pattern and the question mark marks it as "may match once" or "may not match at all".
Note: [0-9]
is equivalent to \d
. I just prefer to actually see the digits.