Regex for monetary values ​​in JavaScript

Some time from the regex game. Trying to come up with something that will allow the user to enter a monetary value either with / without a dollar sign, or with commas. For example, all of the following values ​​must be valid:

 5 5.1 5.10 $5 500,000 500,000.1 500,000.10 $100,000,000.50 etc.... 

Can someone please help me?

+8
javascript regex
source share
4 answers

This should work:

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

A bit more strict with the placement of a comma (for example, rejected 3.2.10):

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

To get a number from it:

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

I have not tested Driven Developement, TDD, for this, using the Qunit framework.

TDD Overview http://net.tutsplus.com/tutorials/javascript-ajax/test-driven-javascript-development-in-practice/

1st: Write tests.

2nd: Verification tests do not work.

3rd: perform a test run.

4th: Refactoring.

 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 is one possible solution to your problem.

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

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

I forgot the refactoring.

+2
source share

^(\$?\d{1,3}(?:,?\d{3})*(?:\.\d{2})?|\.\d{2})?$

It took some time, but I finally got something fully functional. It allows cases such as 100.00, .35, $ ​​1.35, etc. If you exclude entries with inappropriate commas, there are too many numbers between commas or in front of them, or too many numbers after the decimal point.

You can play with him here.

+1
source share
Perhaps it? http://refiddle.com/2tg
 (\$?(:?\d+,?.?)+) 

In addition, http://refiddle.com/2ti ; longer version that does not match digits, e.g. 123,45.4.3

 ^(\$?(:?\d+,?)+(:?.?\d+)?)$ 
0
source share

All Articles