简体   繁体   中英

Javascript Regex allow comma in amount

I have Regex expression which allow user to enter amount with decimal or without decimal . I am facing issue when there is comma(,) in amount. I want to allow comma(,) in amount.

Here is my Regex

var regexp = new RegExp("^\\$?(?=.*[1-9])(?:[1-9]\\d*\\.?|0?\\.)\\d*$")

The above expression works with following amounts

123
1.232
112.2
$12.0
$0.1

It fails with following

$42,529.41
$4,529.41

How can I allow comma in amount? Amount must be greater then zero.

Use a pattern to allow comma in the integer part and make it to repeat zero or more times. Add a negative lookahead to not to match 0 or 0.0 , 00 , etc

var regexp = /^\$?(?!0+(?:\.0+)?$)\d+(?:,\d+)*(?:\.\d+)?$/m;

OR

^(?=.*?[1-9])\$?\d+(?:,\d+)*(?:\.\d+)?$

DEMO

^\\$?(?=.*[1-9])(?:[1-9]\\d*,?\\d*[.]?|0?[.])\\d*$

                            ^^  ^^

Try this.See demo.

https://regex101.com/r/nD5jY4/1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM