Oseer
Oseer

Reputation: 740

Javascript regex for amount

I'm trying to get a regex for an amount:

ANY DIGIT + PERIOD (at least zero, no more than one) + ANY DIGIT (at least zero no more than two [if possible, either zero OR two])

What I have is:

/^\d+\.\{0,1}+\d{0,2)+$/

...obviously not working. Examples of what I'm trying to do:

123 valid

123.00 valid

12.34.5 invalid

123.000 invalid

Trying to match an amount with or without the period. If the period is included, can only be once and no more than two digits after.

Upvotes: 2

Views: 21120

Answers (3)

slandau
slandau

Reputation: 24052

Would something like this work?

// Check if string is currency
var isCurrency_re    = /^\s*(\+|-)?((\d+(\.\d\d)?)|(\.\d\d))\s*$/;
function isCurrency (s) {
   return String(s).search (isCurrency_re) != -1
}

Upvotes: 1

Vivin Paliath
Vivin Paliath

Reputation: 95508

Have you tried:

/^\d+(\.\d{1,2})?$/

The ? makes the group (\.\d{1, 2}) optional (i.e., matches 0 or 1 times).

Upvotes: 2

Matt Ball
Matt Ball

Reputation: 359786

Make the decimal point and 1 or 2 digits after the decimal point into its own optional group:

/^\d+(\.\d{1,2})?$/

Tests:

> var re = /^\d+(\.\d{1,2})?$/
  undefined
> re.test('123')
  true
> re.test('123.00')
  true
> re.test('123.')
  false
> re.test('12.34.5')
  false
> re.test('123.000')
  false

Upvotes: 19

Related Questions