Copy link to clipboard
Copied
Hi All,
I'm trying to validate an inputted value from a form to make sure it is a valid currency value:
I only want to accept a monetary value with 2 decimal places and I do not want to use any JavaScript validation.
CF seems to make this very difficult.
Thanks,
John
Copy link to clipboard
Copied
Server-side validation is the best approach for form validation. As much as I love JavaScript, it can be easily bypassed.
There are a couple of ways, I guess.
One would be to use a REGEX to match the value. REmatch() returns an array of the instances found within the string. If the arrayLen() of the array is not 1, then you can be _reasonably_ sure the entry is not valid.
OR, you could use IsNumeric(), but I've heard of issues with that (ie, "100e100" is a valid numeric value.) Or IsValid(type,string); but that might have issues, too - although you can use REGEX to make sure.
HTH,
^_^
UPDATE: Don't completely discount JavaScript - not for validation, but for masking. There are scripts available that can format the value as it is entered - deny anything that isn't an integer, and automatically format for "0.00" where 0 is any number. Just a thought.
UPDATE2: Oh, and please - don't use CFFORM and the built-in form validation. It's not that good, and you don't have much granular control.
Copy link to clipboard
Copied
An example of validation at the server
<!--- Define your locale. See https://helpx.adobe.com/coldfusion/cfml-reference/coldfusion-functions/functions-s/setlocale.html --->
<cfset newLocale = SetLocale("English (UK)")>
<!--- Initialize --->
<cfset isValueValidCurrency = false>
<cfset validationMsg = "No value submitted.">
<cfif isDefined("form.myValue") and trim(form.myValue) is not "">
<!--- Validate --->
<cfif LSIsCurrency(form.myValue)>
<cfset isValueValidCurrency = true>
<cfset validationMsg = "Value is valid currency in locale " & getLocale()>
<cfoutput>
value: #LSCurrencyFormat(form.myValue)# <br>
msg: #validationMsg#
</cfoutput>
<cfelse>
<cfset validationMsg = "Value '" & form.myValue & "' is not valid currency in locale " & getLocale()>
</cfif>
</cfif>
<cfif isValueValidCurrency>
<!--- Validation succeeded. Proceed with business code --->
<cfelse>
<cfoutput>
Message: #validationMsg# <br>
<form action="#CGI.SCRIPT_NAME#" method="post">
<input name="myValue" type="text">
<input name="sbmt" type="submit" value="Submit">
</form>
</cfoutput>
</cfif>