Been out of the regex
game for a while. Trying to come up with something that will allow the user to enter a money value either with/without dollar sign or with/without commas. For example, all the of the following values should be valid:
5
5.1
5.10
$5
500,000
500,000.1
500,000.10
$100,000,000.50
etc....
Could someone please help me out?
I didn't Test Driven Developement, TDD, for this one using the Qunit framework.
TDD overview http://net.tutsplus.com/tutorials/javascript-ajax/test-driven-javascript-development-in-practice/
1st: Write tests.
2nd: Watch tests fail.
3rd: Make test pass.
4th: Refactor.
Here's one possible solution to your problem.
Demo here: http://jsfiddle.net/vpyV6/
I forgot to refactor though.
Perhaps this? http://refiddle.com/2tg
Also, http://refiddle.com/2ti ; a longer version that doesn't match numbers like 123,45.4.3
^(\$?\d{1,3}(?:,?\d{3})*(?:\.\d{2})?|\.\d{2})?$
This one took a while, but I finally got something fully functional. It allows for cases such as 100.00, .35, $1.35, etc. While excluding entries with misplaced commas, too many numbers in between or before commas, or too many numbers after the decimal point.
You can play around with it here
Example:
$10 or £10 0r €10
but if you use simple10
this will be wrongThis should work:
A little more strict with comma placement (would reject 3,2.10, for example):
To get a number out of it: