Amr Elgarhy
Amr Elgarhy

Reputation: 68922

How to validate currency value using JavaScript?

I have some input fields in a page and i want to validate if they contain currency values such as $100 or with euro.

Any one have an idea or example?

Upvotes: 1

Views: 5802

Answers (2)

cletus
cletus

Reputation: 625097

The problem here is threefold:

  1. There are a lot of currency symbols;
  2. Currencies share the same symbol (does $ mean Australian or US dollars for example); and
  3. Locale differences in writing numbers (eg 3,000.00 in English is 3'000,00 in German).

My advice? Just take numbers and forget about the currency symbol. If however detecting the currency is the whole point then either select that separately or you'll need to implement at least a subset of the above list of currencies plus the locale differences.

Upvotes: 7

nickf
nickf

Reputation: 546065

a regex can validate that for you:

/[\$£¥]\d+(\.\d\d)?/

(but with the euro sign in there too)

this one I've given won't be the most robust way to do it. You could alter to your preference. An alternative is to try something like this:

var myString = "$55.32",
    currency = parseFloat(myString.replace(/^[^\d\.]*/, ''))
    valid = !isNaN(currency)
;

It strips away any non-number or . characters from the start and then parses it as a float.

Upvotes: 2

Related Questions