简体   繁体   中英

Validating Currency on Javascript using a regex not working

I need a regular expression for currency type. Requirements :

1. First char can be a '$'. It can appear either 0 or 1 times.
2. Then a digit can appear multiple times.
3. Then a decimal point can appear either 0 or 1 time.
4. After this, a digit can appear 0 or more times. 

I have written the following regular expression :

\$?\d+\.?\d*

I need to test this on JS . This is how i test this on JS;

var str = "$cng";
var patt = new RegExp('[\$?\d+\.?\d*]');
var res = patt.test(str);
console.log(res);

The above string $cng is returning true. I am not able to get it. Am i missing anything here. Can anyone please help. Thanks in advance.

  1. You must need to escape all the backslashes one more times when passing it to the RegExp constructor which has double quotes as delimiter.

  2. And also i suggest you to remove the square brackets around your pattern.

So change your pattern like below,

var patt = new RegExp("^\\$?\\d+\\.?\\d*$");

OR

var patt = new RegExp("^\\$?\\d+(?:\\.\\d+)?$");

Example:

> var str = "$123.12";
undefined
> var patt = new RegExp("^\\$?\\d+(?:\\.\\d+)?$");
undefined
> patt.test(str);
true
> var patt = new RegExp("^\\$?\\d+(?:\\.\\d+)?$");
undefined
> patt.test('$123.12$');
false
[\$?\d+\.?\d*]==>[] is a character class.

Your regex will just match 1 character out of the all defined inside the character class.

Use

^\\$?\\d+\\.?\\d*$

or

/^\$?\d+\.?\d*$/ 

to be very safe.

Replace RegExp('[\\$?\\d+\\.?\\d*]') with RegExp(/\\$?\\d+\\.?\\d*/) and it will work as expected.

Working Code Snippet:

 var str = "$100.10"; var patt = new RegExp(/^\\$?\\d+\\.?\\d*$/); var res = patt.test(str); console.log(res); 

EDIT:

You can also simply do: var res = /^\\$?\\d+\\.?\\d*$/.test(str);

Your regular expression should also match the beginning and end of the string, otherwise it will only test if the string contains a currency:

^\$?\d+\.?\d*$

You added brackets around the regular expression when you implemented it in Javascript, which changes the meaning entirely. The pattern will find a match if any of the characters within the brackets exist in the string, and as there is a $ in the string the result was true .

Also, when you have a regular expression in a string, you have to escape the backslashes:

var patt = new RegExp('^\\$?\\d+\\.?\\d*$');

You can also use a regular expression literal to create the object:

var patt = /^\$?\d+\.?\d*$/;

You might want to change the requirements so that the decimal point only is allowed if there are digits after it, so that for example $1. is not a valid value:

^\$?\d+(\.\d+)?$

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