regex for money values in JavaScript

2020-03-12 03:14发布

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?

5条回答
Animai°情兽
2楼-- · 2020-03-12 03:39

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.

查看更多
▲ chillily
3楼-- · 2020-03-12 03:53

Perhaps this? http://refiddle.com/2tg

(\$?(:?\d+,?.?)+)

Also, http://refiddle.com/2ti ; a longer version that doesn't match numbers like 123,45.4.3

^(\$?(:?\d+,?)+(?:.?\d+)?)$
查看更多
萌系小妹纸
4楼-- · 2020-03-12 03:57

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

查看更多
5楼-- · 2020-03-12 03:57
var currencyRegex = /^[$£€]\d+(?:\.\d\d)*$/g;

Example: $10 or £10 0r €10 but if you use simple 10 this will be wrong

查看更多
相关推荐>>
6楼-- · 2020-03-12 03:59

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, ''));
  ...
}
查看更多
登录 后发表回答