Doug Conran
Doug Conran

Reputation: 459

Cannot fathom out why Javascript regex not working

I want to validate some input to check that it is a positive currency value of the format:

0.5, 0.55, 5 (note this one), 5.5, 5.55, 55 etc etc.

The code that I'm using is:

  if ($("#gross").val()>0 && !/^\d+?\.?\d?\d$/.test($("#gross").val())) {
    alert($("#gross").val() + " is invalid currency");
  }

It works for everything except a single digit, eg 5 (and 5.) but does work for 5.5.

What am I doing wrong?

Upvotes: 0

Views: 80

Answers (3)

Qantas 94 Heavy
Qantas 94 Heavy

Reputation: 16020

You've forgotten to add a ? at the end, before the $. A better way of doing it would be the following:

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

This checks that there are up to two decimal places for the number - if you'd like to check for any amount, you could use something like:

/^(?!\.$)(?:(?!0\d)(\d*)\.?(\d[0-9]*))$/

Note that it's a good idea to explicitly convert your string into a number, and also cache the value of #gross.

var grossVal = $("#gross").val();
if (+grossVal > 0 && !/^\d+?\.?\d{0,2}$/.test(grossVal)) {
    alert(grossVal + " is invalid currency");
}

Upvotes: 7

thgaskell
thgaskell

Reputation: 13226

+? will match the fewest possible matches, in this case, 1 digit.

I think you're looking for something like:

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

Which would be a series of digits, potentially followed by a decimal and anywhere between 0 to 2 digits.

Upvotes: 2

user2864740
user2864740

Reputation: 61865

Consider using alternation to break down a regular expression into the form a|b|c|d.

Then we can use several different forms, let:

a = 0                       -- 0
b = [1-9]\d*                -- n (non-zero integer), n cannot start with 0
c = 0[.]\d{1,2}             -- 0.x or 0.xy
d = [1-9]\d*[.]\d{1,2}      -- n.x or n.xy, n (non-zero integer)

This will allow us to reject values like 09 and 1., as they are not covered by any of the individual forms accepted.

Upvotes: 1

Related Questions