Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex for money values in JavaScript

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?

like image 318
cakeforcerberus Avatar asked Aug 03 '12 16:08

cakeforcerberus


3 Answers

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, ''));
  ...
}
like image 121
Kip Avatar answered Nov 09 '22 18:11

Kip


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.

like image 30
Larry Battle Avatar answered Nov 09 '22 18:11

Larry Battle


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

like image 1
Riot Goes Woof Avatar answered Nov 09 '22 18:11

Riot Goes Woof