regex for money values in JavaScript

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.

var moneyTest_RE = /^\$?\d+((,\d{3})+)?(\.\d+)?$/;
test("test money format for valid values", function () {
    var moneyArr = ["5","5.1","5.10","$5","500,000","500,000.1","500,000.10","$100,000,000.50", "500,000,100" ];
    var i = moneyArr.length;

    while( i-- ){
        equal( moneyTest_RE.test( moneyArr[ i ] ), true, moneyArr[ i ] + " didn't match completely." );
    }
});
test("test money format for invalid values", function () {
    var moneyArr = ["5..","$$5.1",".5.10","$5.2.","50,0,000",",500,000.1","500,000,10,","$1,00,000,000.50", "500,000,10"];
    var i = moneyArr.length;

    while( i-- ){
        equal( moneyTest_RE.test( moneyArr[ i ] ), false, moneyArr[ i ] + " didn't match completely." );
    }
});

Here's one possible solution to your problem.

var moneyTest_RE = /^\$?\d+((,\d{3})+)?(\.\d+)?$/;  

Demo here: http://jsfiddle.net/vpyV6/

I forgot to refactor though.


This should work:

isValid = str.search(/^\$?[\d,]+(\.\d*)?$/) >= 0;

A little more strict with comma placement (would reject 3,2.10, for example):

isValid = str.search(/^\$?\d+(,\d{3})*(\.\d*)?$/) >= 0;

To get a number out of it:

if(isValid) {
  var num = Number(str.replace(/[\$,]/g, ''));
  ...
}

^(\$?\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