user2733971
user2733971

Reputation: 191

Adjusting a RegEx to require 2 digits after an optional decimal?

I believe I've found the "perfect" Regular Expression to check against for currency in jQuery Validate, except it seems to allow the user to put a single lone decimal at the end or a decimal with a single digit after.

Matches: 700. and 3.0

The Regex:

^\$?([1-9]{1}[0-9]{0,2}(\,[0-9]{3})*(\.[0-9]{0,2})?|[1-9]{1}[0-9]{0,}(\.[0-9]{0,2})?|0(\.[0-9]{0,2})?|(\.[0-9]{1,2})?)$

I've been playing with it in http://gskinner.com/RegExr/ but can't seem to modify it in the right places to fix my decimal issue.

Currently it matches everything I need it to:

700,000 700,000.00 700000

Here is the jQuery validator addMethod using @Kolink's regex for those of you curious:

jQuery.validator.addMethod("currency", function(value, element) {
     return this.optional(element) || /^\$?(?=.)(?:[1-9]\d{0,2}(?:,?\d{3})*)?(?:\.\d{2})?$/.test(value);
}, "Please enter a valid number.");

Upvotes: 2

Views: 1421

Answers (2)

Bohemian
Bohemian

Reputation: 424993

I would do this:

^\$?(?=.)([1-9]\d{0,2}((,\d{3})*|\d*))?(0?\.\d\d)?$

See a live demo of this working with your examples.

Upvotes: 0

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324620

In each case your regex is saying "blah blah blah, then optionally a decimal point followed by zero to two digits".

Try this instead:

^\$?(?=.)(?:[1-9]\d{0,2}(?:,?\d{3})*)?(?:\.\d{2})?$

It's a much simpler regex and it does everything your current one does... but better.

Breaking it down:

  • ^ start of string
  • \$? optional dollar sign
  • (?=.) require at least one character (because your requirement is for the whole part to be optional, and the decimal to be optional, but requires at least one)
  • (?:[1-9]\d{0,2}(?:,?\d{3}))*)? optionally match an integer. This integer may or may not be thousand-separated. Must start with a non-zero digit.
  • (?:\.\d{2})? optionally match a dot followed by two digits.
  • $ end of string

Upvotes: 6

Related Questions