2

I want to check my form field's value whether it's numeric with two decimal and do the validation accordingly. It should accept numeric with two decimals ex: 2.33 else it should throw error like 2.987 it should not accept more than two decimal. Can anyone help me with this?

I have tried following:

<cfif NOT isValid(#NumberFormat( 7.4, ",.00" )#, dataValue)> 
Abhishekh Gupta
  • 6,206
  • 4
  • 18
  • 46

3 Answers3

3

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.

Alex
  • 7,743
  • 1
  • 18
  • 38
1

I don't like using cfinput but in the interest of time:

<cfinput type="text" name="name" mask="9.99"/>
TRose
  • 1,718
  • 1
  • 16
  • 32
1

You can use isValid() along with a regular expression to validate this:

<cfset input = "7.44">
<cfif isValid( "regex", input, "^\d+\.\d{2}$" )>
    <!--- Valid input handler --->

<cfelse>
    <!--- Invalid input handler --->

</cfif>

Here is a GIST.

Note:- Not related to your question but you don't need additional hash in the code that you have tried. You can check more here.

Abhishekh Gupta
  • 6,206
  • 4
  • 18
  • 46