0

I have an ajax form that gets submitted to an iframe. On the server-side I want to validate an input as a valid integer, and if it is not validated set it to a default value of 0. Initial solution was:

<cfparam name="FORM.integerField" default="0" type="integer">

But, on form submit if string data was entered then the server throws an error. I don't want the error to be thrown, I want to check the datatype and set it to a default if it fails the check and then keep processing the from. I have also tried things like:

<cfqueryparam value="#atest#" cfsqltype="CF_SQL_NUMERIC"> <!-- inside my query -->

<cfif IsDefined(LSParseNumber(FORM.integerField))>

<cfif LSParseNumber(FORM.integerField)>

Any suggestions?

Jeff Fabiny
  • 325
  • 2
  • 15

2 Answers2

3
<cfif NOT isValid("integer",FORM.integerField)>
    <cfset FORM.integerField = 0>
</cfif>

I <3 "isValid()".

Sharondio
  • 2,605
  • 13
  • 16
0

This might be overkill for what you want, but it'll do the job. Just supply the number argument.

<cffunction name="CastAsInteger" access="public" returntype="String" output="false" hint="Returns the provided number if it matches the bits and sign, otherwise returns 0">
    <cfargument name="number" type="any" required="true" hint="Any string that may be an integer">
    <cfargument name="bits" type="numeric" default="32" required="false" hint="Number of bits to determine the max size of the integer">
    <cfargument name="signed" type="boolean" default="true" required="false" hint="If the integer is signed or unsigned">

    <cfset local.ReturnInt = Arguments.Number>

    <!--- Make sure it's just a number --->
    <cfif REFind("^-?[1-9]+[0-9]*$", local.ReturnInt) EQ false>
        <cfset local.ReturnInt = 0>
    </cfif>

    <!--- Check size --->
    <cfif Arguments.signed EQ true>
        <cfif local.ReturnInt LT PrecisionEvaluate(-(2^(Arguments.bits - 1))) OR local.ReturnInt GT PrecisionEvaluate((2^(Arguments.bits - 1)) - 1)>
            <cfset local.ReturnInt = 0>
        </cfif>
    <cfelse>
        <cfif local.ReturnInt LT 0 OR local.ReturnInt GT PrecisionEvaluate((2^Arguments.bits) - 1)>
            <cfset local.ReturnInt = 0>
        </cfif>
    </cfif>

    <cfreturn local.ReturnInt>
</cffunction>
nosilleg
  • 2,143
  • 1
  • 22
  • 36