0

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?

1
  • 2
    I fathom that it's a mistake in the regular expression used. Commented Nov 23, 2013 at 0:05

3 Answers 3

7

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");
}
Sign up to request clarification or add additional context in comments.

2 Comments

In JavaScript, \d and [0-9] are the same. In some flavors \d is equivalent to \p{Nd} (Unicode decimal digit), but I don't know of any flavor where it matches letters. Are you perhaps thinking of \w?
@AlanMoore: indeed, don't know what I was thinking. The production CharacterClassEscape :: d evaluates by returning the ten-element set of characters containing the characters 0 through 9 inclusive.
2

+? 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.

Comments

1

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.

3 Comments

Note that the questioner explicitly said that 5. should be accepted by the regular expression ("eg 5 (and 5.)").
@Qantas94Heavy Oh, yeah .. that's buried further down - I just went off of the initial listing. (This doesn't accept that as written, but can be trivially adapted as so.)
Anyway, +1 for suggesting people don't just cram their whole regex into one way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.