仅在coldfusion中使用带有两位小数的数字验证文本字段值

时间:2017-06-15 07:51:58

标签: coldfusion

我想检查我的表单字段的值是否为带有两位小数的数字,并相应地进行验证。它应该接受带有两位小数的数字ex:2.33否则它应该抛出像2.987的错误它不应该接受超过两位小数。任何人都可以帮我这个吗?

我试过以下:

<cfif NOT isValid(#NumberFormat( 7.4, ",.00" )#, dataValue)> 

3 个答案:

答案 0 :(得分:2)

正则表达式是一种很好的验证方法。看看你可以在这里使用哪个选项:

<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>

^ =值必须从即将到来的模式开始 [0-9]+ =匹配0到9之间的数字,一位数或更多数字 \. =一个点(字面意思),反斜杠是一个转义符号,因为.具有不同的效果
[0-9]{2} =匹配0到9的数字,正好是两位数 $ =值必须以前一个模式结束

如果您想接受点和逗号作为小数点分隔符,可以将\.更改为[,.]
如果您想接受一个或两个小数空格,可以将[0-9]{2}更改为[0-9]{1,2}

如果您根本不需要小数位,但当它们存在时,它们必须有两位小数:

<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})? =括号组,模式和问号将其标记为&#34;可以匹配一次&#34;或者&#34;可能根本不匹配&#34;。

注意:[0-9]相当于\d。我只是想看看数字。

答案 1 :(得分:1)

我不喜欢使用cfinput但是为了节省时间:

<cfinput type="text" name="name" mask="9.99"/>

答案 2 :(得分:1)

您可以使用isValid()和正则表达式来验证:

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

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

</cfif>

这是GIST

注意: - 与您的问题无关,但您在尝试的代码中不需要额外的哈希值。您可以查看更多here