Formatting Money for database inserts

Word Count: 351

This is a common problem and I use to come across this a lot. Here is a question from my friend Greg that I find many people scratch their head at.

Do you happen to know if there is any easy way in CF to mask against the use of commas in integer/float fields within a form? We are running into a lot of error on database insert due to the presence of commas (1,234 vs 1234). CF seems to let these through when a form is submitted, and then we get an error on insert.

So the first reaction is to say well why don't we just control what the user enters on the client side while entering a  new record. I really have to points to drive home about this. I don't think you can ever rely on client side validation and what happens when you come to this record to update it? We take the numerical value from the database and format it as money to make it more user friendly.

The easiest way to get around this problem is to strip any formatting characters that might be present before a database insert. I took a quick look around to find something that would help all. I went over to trusty old CFLIB and found this function for converting to a number written by Glenn Wilson. Here is a quick example of a money string and how to convert it for a database insert.

One thing I will try and stress is getting away from the uber utility component that we all seem to create from time to time. You could easily abstract this method into a formatting library. I plan on writing an article shortly on this so stay tuned.

Comments

#1 Posted By: Aaron Posted On: 10/16/08 2:54 PM
fyi.../ is not an escape character \ this, the . also does not need to be escaped in this block. The only time a - would be valid is if it was at the start of the string. For example this says that $50,00-00 is valid, basically because the val() scrubs it. The whole regex even though it is still incorrect could be shortend to [^\d.-]. The fact that strVal is not properly scoped and the random casing of strVal. I realize this was done in 2002 but it just goes to show the amount of bad code that gets put on cflib. Don't get me wrong there is some usable code there, but the majority of it is just plain nasty. Sorry for the rant.
#2 Posted By: Dan Vega Posted On: 10/16/08 2:58 PM |
Author Comment
Please Rant away! I am very weak when it comes to RegEx and it is something I need to get better at. Thanks for the suggestions.
#3 Posted By: Dan Vega Posted On: 10/20/08 11:18 AM |
Author Comment
The post is acting weird, its doubling up the regex. The regex should just be "[^/.0123456789-]";


Post Your Comment

Leave this field empty







Show Captcha

If you subscribe, any new posts to this thread will be sent to your email address.

Copyright © 2007 Dan Vega | BlogCFC was created by Raymond Camden. This blog is running version 5.8.001.