简体   繁体   中英

Javascript regex for currency

I would like to pass only proper currency amounts such as 22.22, 465.56, 1424242.88

I have been using this regex:

[0-9]+\.[0-9][0-9](?:[^0-9a-zA-Z\s\S\D]|$)

But it allows symbols such as £25.55. How can I force only numbers in correct currency format?

Thanks for any help

It sounds like you just haven't provided the anchors on the regex, and you haven't escaped the . . Eg it should be:

var currencyNumbersOnly = /^\d+\.\d{2}$/;

Breakdown:

  • ^ Start of string.

  • \\d A digit (0-9).

  • + One or more of the previous entity (and so \\d+ means "one or more digits").

  • \\. A literal decimal point. Note that some cultures use , rather than . !

  • \\d{2} Exactly two digits.

  • $ End of string.

This isn't hyper-rigorous. For instance, it allows 0000000.00 . It also disallows 2 (requiring 2.00 instead). Also note that even when talking about currency figures, we don't always only go down to the hundreds. Bank exchange rates, for instance, may go on for several places to the right of the decimal point. (For instance, xe.com says that right now, 1 USD = 0.646065 GBP).

And as Jack points out in comments on the question, you may want to allow negative numbers, so throwing a -? (0 or 1 - characters) in there after the ^ may be appropriate:

var currencyNumbersOnly = /^-?\d+\.\d{2}$/;

Update : Now that I can see your full regex, you may want:

var currencyNumbersOnly = /^\d+\.\d{2}(?:[^0-9a-zA-Z\s\S\D]|$)/;

I'm not sure what you're doing with that bit at the end, especially as it seems to say (amongst other things) that you allow a single character as long as it isn't 0-9 and as long as it isn't \\D . As \\D means "not 0-9 ", it's hard to see how something could match that. (And similarly the \\s and \\S in there.)

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