简体   繁体   中英

Validation of price in Javascript using Regex

I need to check whether a string is valid price or not. In some locales, "." is interchanged with "," and separator could be at thousands or hundreds. For Example: Valid:

1234  
1,234
1.234  
1,23,334
1.23.334 
1,23,334.00
1.23.334,00

Invalid:

1,23...233
1,,23
etc

The Regex I have used is

/(\d+(?:[\.,](?![\.,])\d+)*)/g

but this is giving me two matches for "1,23...233" i,e "1,23" and "233" as matches, I don't want to return any matches for that. Here is the regex I have been working on. What I actually want to do, whenever there is "." or "," next character should not be "." or "," and it should be a digit.

Seems like you want something like this,

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

DEMO

OR

^(?!.*(,,|,\.|\.,|\.\.))[\d.,]+$

Negative lookahead at the start asserts that the sting won't contain consecutive commas or dots or dots and commas.

DEMO

You can simply do this.

^\d+(?:[.,]\d+)*$

Try this.See demo.

https://regex101.com/r/tX2bH4/61

var re = /^\d+(?:[.,]\d+)*$/gm;
var str = '1234\n1,234\n1.234\n1,23,334\n1.23.334\n1,23,334.00\n1.23.334,00\n1,23...233\n1,23.';
var m;

while ((m = re.exec(str)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}

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